package cn.stylefeng.guns.modular.storage.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.core.util.ExcelWrite;
import cn.stylefeng.guns.modular.basic.entity.BasicArea;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicGoods;
import cn.stylefeng.guns.modular.basic.entity.BasicOperate;
import cn.stylefeng.guns.modular.basic.entity.BasicTray;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.basic.model.params.BasicGoodsParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicPositionParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicTrayParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicGoodsResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicPositionResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicTrayResult;
import cn.stylefeng.guns.modular.basic.service.BasicAreaService;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicGoodsService;
import cn.stylefeng.guns.modular.basic.service.BasicOperateService;
import cn.stylefeng.guns.modular.basic.service.BasicPositionService;
import cn.stylefeng.guns.modular.basic.service.BasicTrayService;
import cn.stylefeng.guns.modular.basic.service.BasicWarehouseService;
import cn.stylefeng.guns.modular.inventory.model.params.MoveDiskDetailedParam;
import cn.stylefeng.guns.modular.inventory.service.MoveDiskDetailedService;
import cn.stylefeng.guns.modular.order.entity.OrderPut;
import cn.stylefeng.guns.modular.order.model.params.OrderPutDetailedParam;
import cn.stylefeng.guns.modular.order.model.params.OrderPutParam;
import cn.stylefeng.guns.modular.order.model.params.OutOrderDetailedParam;
import cn.stylefeng.guns.modular.order.model.params.OutOrderParam;
import cn.stylefeng.guns.modular.order.model.result.OrderPutDetailedResult;
import cn.stylefeng.guns.modular.order.model.result.OutOrderDetailedResult;
import cn.stylefeng.guns.modular.order.model.result.OutOrderResult;
import cn.stylefeng.guns.modular.order.service.OrderPutDetailedService;
import cn.stylefeng.guns.modular.order.service.OrderPutService;
import cn.stylefeng.guns.modular.order.service.OutOrderDetailedService;
import cn.stylefeng.guns.modular.pandian.model.params.PandianChoupanDetailedParam;
import cn.stylefeng.guns.modular.pandian.model.params.PandianJihuaDetailedParam;
import cn.stylefeng.guns.modular.pandian.service.PandianChoupanDetailedService;
import cn.stylefeng.guns.modular.pandian.service.PandianJihuaDetailedService;
import cn.stylefeng.guns.modular.storage.entity.Kfgoods;
import cn.stylefeng.guns.modular.storage.entity.StorageOutDetailed;
import cn.stylefeng.guns.modular.storage.entity.StoragePutSingle;
import cn.stylefeng.guns.modular.storage.entity.StorageStock;
import cn.stylefeng.guns.modular.storage.mapper.StorageStockMapper;
import cn.stylefeng.guns.modular.storage.model.params.StorageOutDetailedParam;
import cn.stylefeng.guns.modular.storage.model.params.StorageOutParam;
import cn.stylefeng.guns.modular.storage.model.params.StoragePeriodParam;
import cn.stylefeng.guns.modular.storage.model.params.StoragePutParam;
import cn.stylefeng.guns.modular.storage.model.params.StoragePutSingleParam;
import cn.stylefeng.guns.modular.storage.model.params.StorageStockParam;
import cn.stylefeng.guns.modular.storage.model.result.StorageOutDetailedResult;
import cn.stylefeng.guns.modular.storage.model.result.StorageOutResult;
import cn.stylefeng.guns.modular.storage.model.result.StoragePeriodResult;
import cn.stylefeng.guns.modular.storage.model.result.StoragePutResult;
import cn.stylefeng.guns.modular.storage.model.result.StoragePutSingleResult;
import cn.stylefeng.guns.modular.storage.model.result.StorageStockResult;
import cn.stylefeng.guns.modular.storage.service.StorageOutDetailedService;
import cn.stylefeng.guns.modular.storage.service.StorageOutService;
import cn.stylefeng.guns.modular.storage.service.StoragePeriodService;
import cn.stylefeng.guns.modular.storage.service.StoragePutService;
import cn.stylefeng.guns.modular.storage.service.StoragePutSingleService;
import cn.stylefeng.guns.modular.storage.service.StorageStockDetailedService;
import cn.stylefeng.guns.modular.storage.service.StorageStockService;
import cn.stylefeng.guns.modular.system.model.params.SysSwitchParam;
import cn.stylefeng.guns.modular.system.model.result.SysSwitchResult;
import cn.stylefeng.guns.modular.system.service.SysSwitchService;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.DictService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * 库存表 服务实现类
 */
@Service
public class StorageStockServiceImpl extends ServiceImpl<StorageStockMapper, StorageStock> implements StorageStockService {

	@Resource
	private SysSwitchService sysSwitchService;

    @Resource
    private StorageStockService storageStockService;

    @Resource
    private OutOrderDetailedService outOrderDetailedService;
    
    @Resource
    private StoragePutService storagePutService;

    @Resource
    private OrderPutService orderPutService;

    @Resource
    private BasicCustomerService basicCustomerService;

    @Resource
    private BasicPositionService basicPositionService;

    @Resource
    private BasicTrayService basicTrayService;

    @Resource
    private UserService userService;
    
    @Resource
    private BasicGoodsService basicGoodsService;

	@Resource
	private BasicWarehouseService basicWarehouseService;

    @Resource
    private DictService dictService;

    @Resource
    private StorageOutDetailedService storageOutDetailedService;
    @Resource

    private StorageOutService storageOutService;

	@Resource
    private BasicOperateService basicOperateService;

    @Override
    public void add(StorageStockParam param){
        StorageStock entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(StorageStockParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(StorageStockParam param){
        StorageStock oldEntity = getOldEntity(param);
        StorageStock newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public StorageStockResult findBySpec(StorageStockParam param){
        return this.baseMapper.findBySpec(param);
    }

	/**
	 * 获取当前日期 yyyy-MM-dd
	 * @param
	 * @return
	 */
	public static String getDatesssss() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		return format.format(new Date());
	}

	@Override
	public StorageStockResult findById(Integer id){
		return this.baseMapper.findById(id);
	}

    @Override
    public List<StorageStockResult> findListBySpec(StorageStockParam param,Long operateId){
        return baseMapper.findListBySpec(param,operateId);
    }

    @Override
    public List<StorageStockResult> findExportToExcelBySpec(StorageStockParam param,Long operateId){
        return baseMapper.findExportToExcelBySpec(param,operateId);
    }

    @Override
    public LayuiPageInfo findPageBySpec(StorageStockParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(StorageStockParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private StorageStock getOldEntity(StorageStockParam param) {
        return this.getById(getKey(param));
    }

    private StorageStock getEntity(StorageStockParam param) {
        StorageStock entity = new StorageStock();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }
    
	@Override
	@Transactional(rollbackFor = Exception.class,timeout=40)
	public void batchAddNewNew(List<StoragePutSingleResult> ulist,User user) {
		List<StorageStockParam> ssPlist = new ArrayList<StorageStockParam>();//库存list
		StorageStockParam ssP = new StorageStockParam();//库存输入类
		BasicPositionParam bpp = new BasicPositionParam();//库位输入类
		BasicTrayParam btp = new BasicTrayParam();//托盘输入类
		
		StoragePutParam spp = new StoragePutParam();
		spp.setStorageNumber(ulist.get(0).getStorageNumber());
		StoragePutResult spr =  storagePutService.findBySpec(spp);//入库单信息
		BasicCustomer bc  = basicCustomerService.getById(spr.getCustomerId());//客户信息
		BasicWarehouse bw = basicWarehouseService.getById(spr.getWarehouseId());
		
		Long deliverId = user.getDeliverId();
		Long deptId = user.getDeptId();
		
		for (StoragePutSingleResult sPs : ulist) {
			BasicPositionResult bpr = null;
			if(ToolUtil.isNotEmpty(sPs.getPositionNumber())) {
				bpp.setPositionNumber(sPs.getPositionNumber());
				bpp.setDeliverId(deliverId);
				bpp.setWarehouseId(Integer.parseInt(spr.getWarehouseId().toString()));
				bpr = basicPositionService.findBySpec(bpp,deptId,user.getOperateId() );//库位信息
			}
			btp.setTrayNumber(sPs.getTrayNumber());
			btp.setDeptId(deptId);
			BasicTrayResult bTr = basicTrayService.findBySpec(btp,user.getOperateId());
			if(sPs.getStockId() == null) {
				ssP.setStockstate("NOT_RECEIVED");
				ssP.setGoodsId(sPs.getGoodsId());//商品id
				ssP.setTrayNumber(bTr.getTrayNumber());//托盘编号
				ssP.setCustomerId(Long.parseLong(bc.getId().toString()));//客户id
				ssP.setCustomerName(bc.getCustomerName());//客户名称
				ssP.setOperateId(Long.parseLong(bw.getWarehouseOperateId().toString()));//分公司id
				ssP.setOperateName(bw.getWarehouseOperateName());//分公司名称
				ssP.setWarehouseId(spr.getWarehouseId());//仓库id
				ssP.setWarehouseName(spr.getWarehouseName());//仓库名称
				if(bpr != null) {
					ssP.setAreaId(Long.parseLong(bpr.getPositionAreaId().toString()));//库区id
					ssP.setAreaNumber(bpr.getAreaNumber());//库区编号
					ssP.setPositionId(Long.parseLong(bpr.getId().toString()));//库位id
					ssP.setPositionNumber(bpr.getPositionNumber());//库位编号
				}
				ssP.setTrayId(Long.parseLong(bTr.getId().toString()));//托盘id
				ssP.setGoodsName(sPs.getGoodsname());//商品名称
				ssP.setGoodsNumber(sPs.getGoodsNumber());//商品编号
				ssP.setNum(sPs.getPutNum());//数量
				ssP.setBalenum(sPs.getPutBalenum());//大包数
				ssP.setCanNum(sPs.getPutNum());//可用数量
				ssP.setStockWeight(sPs.getPutWeight());//重量
				ssP.setStockVolume(sPs.getDetailedPutvolume());//体积
				ssP.setUnitprice(sPs.getUnitprice());//单价
				ssP.setStockMoney(sPs.getSingleMoney());//金额
				ssP.setProducetime(sPs.getSingleDateofmanufacture());//生产日期
				ssP.setGoodsbatchs(sPs.getSingleBatchnumber());//批次
				ssP.setDeliverId(deliverId);
				ssP.setDeptId(deptId);
				ssP.setCreateTime(new Date());
				ssP.setCreateUser(user.getUserId());
				ssPlist.add(ssP);
				storageStockService.addReturnId(ssP);
				
				StoragePutSingleParam storagePutSingleParam = new StoragePutSingleParam();
				storagePutSingleParam.setId(sPs.getId());
				storagePutSingleParam.setStockId(Long.parseLong(ssP.getId().toString()));
				storagePutSingleService.update(storagePutSingleParam);//更新库存id
			}
            	
			ssP = new StorageStockParam();
			bpp = new BasicPositionParam();
			btp = new BasicTrayParam();
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class,timeout=40)
	public void batchAddNew(List<StoragePutSingle> ulist,User user) {
		List<StorageStockParam> ssPlist = new ArrayList<StorageStockParam>();//库存list
		StorageStockParam ssP = new StorageStockParam();//库存输入类
		BasicPositionParam bpp = new BasicPositionParam();//库位输入类
		BasicTrayParam btp = new BasicTrayParam();//托盘输入类
		
		StoragePutParam spp = new StoragePutParam();
		spp.setStorageNumber(ulist.get(0).getStorageNumber());
		StoragePutResult spr =  storagePutService.findBySpec(spp);//入库单信息
		BasicCustomer bc  = basicCustomerService.getById(spr.getCustomerId());//客户信息
		BasicWarehouse bw = basicWarehouseService.getById(spr.getWarehouseId());
		
		Long deliverId = user.getDeliverId();
		Long deptId = user.getDeptId();
		
		for (StoragePutSingle sPs : ulist) {
			bpp.setPositionNumber(sPs.getPositionNumber());
			bpp.setDeliverId(deliverId);
			bpp.setWarehouseId(Integer.parseInt(spr.getWarehouseId().toString()));
			BasicPositionResult bpr = basicPositionService.findBySpec(bpp,deptId,user.getOperateId());//库位信息
			btp.setTrayNumber(sPs.getTrayNumber());
			btp.setDeptId(user.getDeptId());
			BasicTrayResult bTr = basicTrayService.findBySpec(btp,user.getOperateId());
			ssP.setCustomerId(Long.parseLong(bc.getId().toString()));//客户id
			ssP.setCustomerName(bc.getCustomerName());//客户名称
			ssP.setOperateId(Long.parseLong(bw.getWarehouseOperateId().toString()));//分公司id
			ssP.setOperateName(bw.getWarehouseOperateName());//分公司名称
			ssP.setWarehouseId(spr.getWarehouseId());//仓库id
			ssP.setWarehouseName(spr.getWarehouseName());//仓库名称
			ssP.setAreaId(Long.parseLong(bpr.getPositionAreaId().toString()));//库区id
			ssP.setAreaNumber(bpr.getAreaNumber());//库区编号
			ssP.setPositionId(Long.parseLong(bpr.getId().toString()));//库位id
			ssP.setPositionNumber(bpr.getPositionNumber());//库位编号
			ssP.setTrayId(Long.parseLong(bTr.getId().toString()));//托盘id
			ssP.setTrayNumber(bTr.getTrayNumber());//托盘编号
			ssP.setGoodsId(sPs.getGoodsId());//商品id
			ssP.setGoodsName(sPs.getGoodsname());//商品名称
			ssP.setGoodsNumber(sPs.getGoodsNumber());//商品编号
			ssP.setNum(sPs.getPutNum());//数量
			ssP.setBalenum(sPs.getPutBalenum());//大包数
			ssP.setCanNum(sPs.getPutNum());//可用数量
			ssP.setStockWeight(sPs.getPutWeight());//重量
			ssP.setStockVolume(sPs.getDetailedPutvolume());//体积
			ssP.setUnitprice(sPs.getUnitprice());//单价
			ssP.setStockMoney(sPs.getSingleMoney());//金额
			ssP.setProducetime(sPs.getSingleDateofmanufacture());//生产日期
			ssP.setGoodsbatchs(sPs.getSingleBatchnumber());//批次
			ssP.setDeliverId(deliverId);
			ssP.setDeptId(deptId);
			ssP.setCreateTime(new Date());
			ssP.setCreateUser(user.getUserId());
			ssP.setStockstate("NOT_RECEIVED");
			ssPlist.add(ssP);
			ssP = new StorageStockParam();
			bpp = new BasicPositionParam();
			btp = new BasicTrayParam();
		}
		if (ssPlist.size()>0) {
			storageStockService.batchAddList(ssPlist);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class,timeout=40)
	public void batchAdd(List<StoragePutSingle> ulist) {
		List<StorageStockParam> ssPlist = new ArrayList<StorageStockParam>();//库存list
		StorageStockParam ssP = new StorageStockParam();//库存输入类
		BasicPositionParam bpp = new BasicPositionParam();//库位输入类
		BasicTrayParam btp = new BasicTrayParam();//托盘输入类
		
		StoragePutParam spp = new StoragePutParam();
		spp.setStorageNumber(ulist.get(0).getStorageNumber());
		StoragePutResult spr =  storagePutService.findBySpec(spp);//入库单信息
		BasicCustomer bc  = basicCustomerService.getById(spr.getCustomerId());//客户信息
		BasicWarehouse bw = basicWarehouseService.getById(spr.getWarehouseId());
		
		User user = userService.getcurrentUser();
		Long deliverId = user.getDeliverId();
		Long deptId = user.getDeptId();
		
		for (StoragePutSingle sPs : ulist) {
			bpp.setPositionNumber(sPs.getPositionNumber());
			bpp.setDeliverId(deliverId);
			bpp.setWarehouseId(Integer.parseInt(spr.getWarehouseId().toString()));
			BasicPositionResult bpr = basicPositionService.findBySpec(bpp,deptId,user.getOperateId());//库位信息
			btp.setTrayNumber(sPs.getTrayNumber());
			btp.setDeptId(user.getDeptId());
			BasicTrayResult bTr = basicTrayService.findBySpec(btp,user.getOperateId());
			ssP.setCustomerId(Long.parseLong(bc.getId().toString()));//客户id
			ssP.setCustomerName(bc.getCustomerName());//客户名称
			ssP.setOperateId(Long.parseLong(bw.getWarehouseOperateId().toString()));//分公司id
			ssP.setOperateName(bw.getWarehouseOperateName());//分公司名称
			ssP.setWarehouseId(spr.getWarehouseId());//仓库id
			ssP.setWarehouseName(spr.getWarehouseName());//仓库名称
			ssP.setAreaId(Long.parseLong(bpr.getPositionAreaId().toString()));//库区id
			ssP.setAreaNumber(bpr.getAreaNumber());//库区编号
			ssP.setPositionId(Long.parseLong(bpr.getId().toString()));//库位id
			ssP.setPositionNumber(bpr.getPositionNumber());//库位编号
			ssP.setTrayId(Long.parseLong(bTr.getId().toString()));//托盘id
			ssP.setTrayNumber(bTr.getTrayNumber());//托盘编号
			ssP.setGoodsId(sPs.getGoodsId());//商品id
			ssP.setGoodsName(sPs.getGoodsname());//商品名称
			ssP.setGoodsNumber(sPs.getGoodsNumber());//商品编号
			ssP.setNum(sPs.getPutNum());//数量
			ssP.setBalenum(sPs.getPutBalenum());//大包数
			ssP.setCanNum(sPs.getPutNum());//可用数量
			ssP.setStockWeight(sPs.getPutWeight());//重量
			ssP.setStockVolume(sPs.getDetailedPutvolume());//体积
			ssP.setUnitprice(sPs.getUnitprice());//单价
			ssP.setStockMoney(sPs.getSingleMoney());//金额
			ssP.setProducetime(sPs.getSingleDateofmanufacture());//生产日期
			ssP.setGoodsbatchs(sPs.getSingleBatchnumber());//批次
			ssP.setDeliverId(deliverId);
			ssP.setDeptId(deptId);
			ssP.setCreateTime(new Date());
			ssP.setCreateUser(userService.getcurrentUser().getUserId());
			ssP.setStockstate("NOT_RECEIVED");
			ssPlist.add(ssP);
			ssP = new StorageStockParam();
			bpp = new BasicPositionParam();
			btp = new BasicTrayParam();
		}
		if (ssPlist.size()>0) {
			storageStockService.batchAddList(ssPlist);
		}
	}

	@Override
	public boolean batchAddList(List<StorageStockParam> ssPlist) {
		return this.baseMapper.batchAddList(ssPlist);
	}

    @Override
    public List<StorageStockResult> finByOnlyOne(StorageStockParam sp) {
        return this.baseMapper.finByOnlyOne(sp);
    }

    @Override
    public boolean updateBatchList(List<StorageStock> splist) {
        return this.baseMapper.updateBatchList(splist);
    }

	@Override
	public List<StorageStockResult> findListByparamList(List<StorageStockParam> ssrlist) {
        return this.baseMapper.findListByparamList(ssrlist);
	}

	@Override
	public StorageStockResult findTotalBySpec(StorageStockParam storageStockParam,Long operateId) {
	        return this.baseMapper.findTotalBySpec(storageStockParam,operateId);
	}

	@Override
	public List<StorageStockResult> findGoodsProportion(StorageStockParam storageStockParam) {
        return this.baseMapper.findGoodsProportion(storageStockParam);
	}

	@Override
	public StorageStockResult findTotalgoodsTypeBySpec(StorageStockParam storageStockParam,Long operateId) {
        return this.baseMapper.findTotalgoodsTypeBySpec(storageStockParam,operateId);
	}

	@Override
	public LayuiPageInfo findGoodsListBySpec(StorageStockParam storageStockParam) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.findGoodsListBySpec(pageContext, storageStockParam);
        return LayuiPageFactory.createPageInfo(page);
	}

	@Override
	public List<StorageStockResult> findGoodsList(StorageStockParam storageStockParam,Long operateId) {
		return this.baseMapper.findGoodsList(storageStockParam,operateId);
	}

	@Override
	public List<StorageStockResult> findTrayList(StorageStockParam storageStockParam) {
		return this.baseMapper.findTrayList(storageStockParam);
	}

	@Override
	public  List<StorageStockResult> totalGoodsVolumeList(StorageStockParam storageStockParam,Long operateId) {
		return this.baseMapper.totalGoodsVolumeList(storageStockParam,operateId);
	}


	@Override
	public StorageStockResult findByTrayId(StorageStockParam storageStockParam) {
		return this.baseMapper.findByTrayId(storageStockParam);
	}

	@Override
	public StorageStockResult findByTrayIdall(StorageStockParam storageStockParam) {
		return this.baseMapper.findByTrayIdall(storageStockParam);
	}

	@Override
	public StorageStockResult findSumBySpec(StorageStockParam param) {
		return this.baseMapper.findSumBySpec(param);
	}

	@Override
	public LayuiPageInfo findPageGroupByGoodsIdBySpec(StorageStockParam param,Long diskId, String condition) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.findPageGroupByGoodsIdBySpec(pageContext, param,diskId,condition);
        return LayuiPageFactory.createPageInfo(page);
	}

	@Override
	public LayuiPageInfo findPageDetailedBySpec(StorageStockParam param) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.findPageDetailedBySpec(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
	}

	@Override
	public StorageStockResult findFixedTotal(StorageStockParam ssp) {
		return this.baseMapper.findFixedTotal(ssp);
	}

	@Override
	public StorageStockResult findTotalBySpecms(StorageStockParam storageStockParam,Long operateId) {
		return this.baseMapper.findTotalBySpecms(storageStockParam,operateId);
	}

	@Override
	public LayuiPageInfo findGoodsListBySpecms(StorageStockParam storageStockParam) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.findGoodsListBySpecms(pageContext, storageStockParam);
        return LayuiPageFactory.createPageInfo(page);
	}

	@Override
	public List<StorageStockResult> moveQueryGoods(StorageStockParam param,Long operateId) {
		return this.baseMapper.moveQueryGoods(param,operateId);
	}

	@Override
	public List<StorageStockResult> findDetailedBySpec(StorageStockParam param) {
		return this.baseMapper.findDetailedBySpec(param);
	}

	@Override
	public LayuiPageInfo findStockPageBySpec(StorageStockParam storageStockParam
    		, String startPutTime,String endPutTime
			, String startSingleTime, String endSinglePutTime,Long operateId) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.findStockPageBySpec(pageContext, storageStockParam,startPutTime,endPutTime,startSingleTime,endSinglePutTime, operateId);
        return LayuiPageFactory.createPageInfo(page);
	}

	@Override
	public StorageStockResult findByGoods(StorageStockParam stockParam,Long operateId) {
		return this.baseMapper.findByGoods(stockParam,operateId);
	}

	@Override
	public List<StorageStockResult> checkPositionGoodsNum(StorageStockParam param) {
		return this.baseMapper.checkPositionGoodsNum(param);
	}

	@Override
	public int findTrayListRecommend(StorageStockParam param) {
		return this.baseMapper.findTrayListRecommend(param);
	}
    
	/**
	 * 矫正库存
	 */
	@Override
	public boolean correctNew(MoveDiskDetailedParam moveDiskDetailedParam,User user) {
		SysSwitchParam dParam = new SysSwitchParam();
		dParam.setDeliverId(user.getDeliverId());
		dParam.setDeptId(user.getDeptId());
		dParam.setCode("correct_switch");
		SysSwitchResult dResult = sysSwitchService.findBySpec(dParam,user.getOperateId());
		if (dResult!=null) {
			if (ToolUtil.isNotEmpty(dResult.getOperation())) {
				if ("Y".equals(dResult.getOperation())) {
					if(moveDiskDetailedParam.getNum().equals("0")) {
						increaseNew(moveDiskDetailedParam,user);
					} else {
						BasicGoods basicGoods = basicGoodsService.getById(moveDiskDetailedParam.getGoodsId());
						StorageStockParam param = new StorageStockParam();
						param.setGoodsId(moveDiskDetailedParam.getGoodsId());
						param.setPositionNumber(moveDiskDetailedParam.getPositionNumber());
						param.setTrayNumber(moveDiskDetailedParam.getTrayNumber());
						param.setGoodsbatchs(moveDiskDetailedParam.getGoodsbatchs());
						List<StorageStockResult> list = this.findListBySpec(param,null);
						if (list.size()==0) {
							return false;
						}
						
						BigDecimal num = new BigDecimal(moveDiskDetailedParam.getNum());//库存
						
						BigDecimal sssnum = new BigDecimal(0);//校验是否发生变化
						for (StorageStockResult sss : list) {
							BigDecimal num2 = new BigDecimal(sss.getNum());
							sssnum = sssnum.add(num2);
						}
						if (num.compareTo(sssnum)!=0) {
							return false;
						}
						
						BigDecimal trueNum = new BigDecimal(moveDiskDetailedParam.getTrueNum());//实际
						BigDecimal differ = num.subtract(trueNum);//相差数
						BigDecimal decimal = trueNum.subtract(num);//相差数
						BigDecimal as = new BigDecimal(0);//0
						if (trueNum.compareTo(as)==0) {//盘0
							for (StorageStockResult result : list) {
								ToolUtil.copyProperties(result, param);
				                storageStockDetailedService.addNewDetailed("Inventory Management", "", "Inventory Shortage", "", param,user);
								this.delete(param);
								
								try {
									StorageStockParam param2 = new StorageStockParam();
									param2.setTrayId(param.getTrayId());
									StorageStockResult storageStockResult = this.findBySpec(param2);
									if (storageStockResult == null) {
										BasicTrayParam basicTrayParam = new BasicTrayParam();
										basicTrayParam.setId(Integer.parseInt(param.getTrayId().toString()));
										basicTrayParam.setTrayState("IDLE");
										basicTrayService.update(basicTrayParam);
									}
								} catch (Exception e) {
								}
							}
						} else if (trueNum.compareTo(num) == -1) {//少了
							for (StorageStockResult result : list) {
								StorageStockResult r = result;
								BigDecimal nums = new BigDecimal(r.getNum());//一托数
								if (differ.compareTo(as)==0) {
									break;
								}
								if (nums.compareTo(differ)==1) {//可以减完
									BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume());
									BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());
									BigDecimal p = new BigDecimal(basicGoods.getGoodsCharging());
									BigDecimal s = nums.subtract(differ);
//									r.setProducetime(moveDiskDetailedParam.getNewgoodsbatchs());
//									r.setGoodsbatchs(moveDiskDetailedParam.getNewgoodsbatchs().replaceAll("-", ""));
									r.setNum(s.toString());
									r.setBalenum(s.toString());
									r.setCanNum(s.toString());
									r.setStockVolume(s.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
									r.setStockWeight(s.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
									r.setStockMoney(s.multiply(p).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
									ToolUtil.copyProperties(r, param);
					                storageStockDetailedService.addNewDetailed("Inventory Management", "", "Inventory Shortage", "Original Inventory:"+nums.toString(), param,user);
									this.update(param);
									break;
								} else {
									differ = differ.subtract(nums);
									ToolUtil.copyProperties(r, param);
					                storageStockDetailedService.addNewDetailed("Inventory Management", "", "Inventory Shortage", "Original Inventory:"+nums.toString(), param,user);
									this.delete(param);
									
									try {
										StorageStockParam param2 = new StorageStockParam();
										param2.setTrayId(param.getTrayId());
										StorageStockResult storageStockResult = this.findBySpec(param2);
										if (storageStockResult == null) {
											BasicTrayParam basicTrayParam = new BasicTrayParam();
											basicTrayParam.setId(Integer.parseInt(param.getTrayId().toString()));
											basicTrayParam.setTrayState("IDLE");
											basicTrayService.update(basicTrayParam);
										}
									} catch (Exception e) {
									}
								}
							}
						} else {//盘盈
							BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume());
							BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());
							BigDecimal p = new BigDecimal(basicGoods.getGoodsCharging());
							StorageStockResult result = list.get(0);
							BigDecimal xt = new BigDecimal(result.getNum());
							BigDecimal nums = new BigDecimal(result.getNum());//一托数
							xt = xt.add(decimal);
//							result.setProducetime(moveDiskDetailedParam.getNewgoodsbatchs());
//							result.setGoodsbatchs(moveDiskDetailedParam.getNewgoodsbatchs().replaceAll("-", ""));
							result.setNum(xt.toString());
							result.setBalenum(xt.toString());
							result.setCanNum(xt.toString());
							result.setStockVolume(xt.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
							result.setStockWeight(xt.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
							result.setStockMoney(xt.multiply(p).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
							ToolUtil.copyProperties(result, param);
			                storageStockDetailedService.addNewDetailed("Inventory Management", "", "Inventory Surplus", "Original Inventory:"+nums.toString(), param,user);
							this.update(param);
						}
					}
				} 
			}
		}
        moveDiskDetailedService.add(moveDiskDetailedParam);
		return true;
	}

	@Override
	public boolean correctJhua(PandianJihuaDetailedParam pandianJihuaDetailedParam, User user) {
		if(pandianJihuaDetailedParam.getPanType().equals("新增")) {
			increaseJhua(pandianJihuaDetailedParam,user);
		} else {
			BasicGoods basicGoods = basicGoodsService.getById(pandianJihuaDetailedParam.getGoodsId());
			StorageStockParam param = new StorageStockParam();
			param.setGoodsId(pandianJihuaDetailedParam.getGoodsId());
			param.setPositionNumber(pandianJihuaDetailedParam.getPositionNumber());
			param.setTrayNumber(pandianJihuaDetailedParam.getTrayNumber());
			param.setGoodsbatchs(pandianJihuaDetailedParam.getGoodsbatchs());
			List<StorageStockResult> list = this.findListBySpec(param,null);
			if (list.size()==0) {
				return false;
			}
			
			BigDecimal num = new BigDecimal(pandianJihuaDetailedParam.getNum());//库存
			
			BigDecimal sssnum = new BigDecimal(0);//校验是否发生变化
			for (StorageStockResult sss : list) {
				BigDecimal num2 = new BigDecimal(sss.getNum());
				sssnum = sssnum.add(num2);
			}
			if (num.compareTo(sssnum)!=0) {
				return false;
			}
			
			BigDecimal trueNum = new BigDecimal(pandianJihuaDetailedParam.getTrueNum());//实际
			BigDecimal differ = num.subtract(trueNum);//相差数
			BigDecimal decimal = trueNum.subtract(num);//相差数
			BigDecimal as = new BigDecimal(0);//0
			if (trueNum.compareTo(as)==0) {//盘0
				for (StorageStockResult result : list) {
					ToolUtil.copyProperties(result, param);
	                storageStockDetailedService.addNewDetailed("盘点", pandianJihuaDetailedParam.getDiskName(), "库存缺失", "", param,user);
					this.delete(param);
					
					try {
						StorageStockParam param2 = new StorageStockParam();
						param2.setTrayId(param.getTrayId());
						StorageStockResult storageStockResult = this.findBySpec(param2);
						if (storageStockResult == null) {
							BasicTrayParam basicTrayParam = new BasicTrayParam();
							basicTrayParam.setId(Integer.parseInt(param.getTrayId().toString()));
							basicTrayParam.setTrayState("IDLE");
							basicTrayService.update(basicTrayParam);
						}
					} catch (Exception e) {
					}
				}
			} else if (trueNum.compareTo(num) == -1) {//少了
				for (StorageStockResult result : list) {
					StorageStockResult r = result;
					BigDecimal nums = new BigDecimal(r.getNum());//一托数
					if (differ.compareTo(as)==0) {
						break;
					}
					if (nums.compareTo(differ)==1) {//可以减完
						BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume());
						BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());
						BigDecimal p = new BigDecimal(basicGoods.getGoodsCharging());
						BigDecimal s = nums.subtract(differ);
						r.setGoodsbatchs(pandianJihuaDetailedParam.getNewGoodsbatchs());
						r.setNum(s.toString());
						r.setBalenum(s.toString());
						r.setCanNum(s.toString());
						r.setStockVolume(s.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
						r.setStockWeight(s.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
						r.setStockMoney(s.multiply(p).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
						ToolUtil.copyProperties(r, param);
		                storageStockDetailedService.addNewDetailed("盘点", pandianJihuaDetailedParam.getDiskName(), "库存缺少", "原库存："+nums.toString(), param,user);
						this.update(param);
						break;
					} else {
						differ = differ.subtract(nums);
						ToolUtil.copyProperties(r, param);
		                storageStockDetailedService.addNewDetailed("盘点", pandianJihuaDetailedParam.getDiskName(), "库存缺少", "原库存："+nums.toString(), param,user);
						this.delete(param);
						
						try {
							StorageStockParam param2 = new StorageStockParam();
							param2.setTrayId(param.getTrayId());
							StorageStockResult storageStockResult = this.findBySpec(param2);
							if (storageStockResult == null) {
								BasicTrayParam basicTrayParam = new BasicTrayParam();
								basicTrayParam.setId(Integer.parseInt(param.getTrayId().toString()));
								basicTrayParam.setTrayState("IDLE");
								basicTrayService.update(basicTrayParam);
							}
						} catch (Exception e) {
						}
					}
				}
			} else {//盘盈
				StorageStockResult result = list.get(0);
				BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume());
				BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());
				BigDecimal p = new BigDecimal(basicGoods.getGoodsCharging());
				BigDecimal xt = new BigDecimal(result.getNum());
				BigDecimal nums = new BigDecimal(result.getNum());//一托数
				xt = xt.add(decimal);
				result.setGoodsbatchs(pandianJihuaDetailedParam.getNewGoodsbatchs());
				result.setNum(xt.toString());
				result.setBalenum(xt.toString());
				result.setCanNum(xt.toString());
				result.setStockVolume(xt.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
				result.setStockWeight(xt.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
				result.setStockMoney(xt.multiply(p).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
				ToolUtil.copyProperties(result, param);
                storageStockDetailedService.addNewDetailed("盘点", pandianJihuaDetailedParam.getDiskName(), "库存多出", "原库存："+nums.toString(), param,user);
				this.update(param);
			}
		}
		return true;
	}

	@Resource
    private DeptService deptService;
	
	/**
	 * 获取所属项目单号前缀
	 * @param user
	 * @return
	 */
	public String getOperateIdOrderPrefix(User user) {
		if(user.getOperateId() != null) {
			Dept dept = new Dept();
			dept.setOperateId(user.getOperateId());
			Dept resdept = deptService.findBySpec(dept);
			if(resdept != null) {
				if(ToolUtil.isNotEmpty(resdept.getOrderPrefix())) {
					return resdept.getOrderPrefix();
				} else {
					return user.getAccount().substring(0, 3);
				}
			} else {
				return null;
			}
		} else {
			return null;
		}
	}
	
	private void increaseJhua(PandianJihuaDetailedParam pandianJihuaDetailedParam, User user) {
		Integer id = pandianJihuaDetailedParam.getId();
		Long deliverId = user.getDeliverId();
		Long deptId = user.getDeptId();
		String trayCode = getOperateIdOrderPrefix(user)+"-";
		
		BasicGoods bG = basicGoodsService.getById(pandianJihuaDetailedParam.getGoodsId());//商品
		BasicWarehouse basicWarehouse = basicWarehouseService.getById(pandianJihuaDetailedParam.getWarehouseId());
		BasicArea basicArea = basicAreaService.getById(pandianJihuaDetailedParam.getAreaId());
		StorageStockParam storageStockParam = new StorageStockParam();
		storageStockParam.setOperateId(Long.parseLong(basicWarehouse.getWarehouseOperateId().toString()));
		storageStockParam.setOperateName(basicWarehouse.getWarehouseOperateName());
		storageStockParam.setCustomerId(Long.parseLong(bG.getGoodsCustomerId().toString()));
		storageStockParam.setCustomerName(bG.getGoodsCustomerName());
		storageStockParam.setWarehouseId(pandianJihuaDetailedParam.getWarehouseId());
		storageStockParam.setWarehouseName(basicWarehouse.getWarehouseName());
		storageStockParam.setAreaId(pandianJihuaDetailedParam.getAreaId());
		storageStockParam.setAreaNumber(basicArea.getAreaNumber());
		storageStockParam.setPositionId(pandianJihuaDetailedParam.getPositionId());
		storageStockParam.setPositionNumber(pandianJihuaDetailedParam.getPositionNumber());
		storageStockParam.setGoodsId(pandianJihuaDetailedParam.getGoodsId());
		storageStockParam.setGoodsName(pandianJihuaDetailedParam.getGoodsName());
		storageStockParam.setGoodsNumber(pandianJihuaDetailedParam.getGoodsNumber());
		if(ToolUtil.isEmpty(pandianJihuaDetailedParam.getGoodsbatchs())) {
			storageStockParam.setGoodsbatchs(DateUtil.getDate().replaceAll("-", ""));
		} else {
			storageStockParam.setGoodsbatchs(pandianJihuaDetailedParam.getGoodsbatchs());
		}
		if(ToolUtil.isEmpty(pandianJihuaDetailedParam.getNewGoodsbatchs())) {
			storageStockParam.setProducetime(DateUtil.getDate());
		} else {
			storageStockParam.setProducetime(pandianJihuaDetailedParam.getNewGoodsbatchs());
		}
		storageStockParam.setPutTime(DateUtil.getDate());
		storageStockParam.setStockstate("IN_STOCK");
		storageStockParam.setDeliverId(deliverId);
		storageStockParam.setDeptId(deptId);
		storageStockParam.setUnitprice(bG.getGoodsCharging());
		
		//托盘信息
		BasicTrayParam Tp = new BasicTrayParam();
		BasicTray basicTray = basicTrayService.findByThelastone();
		Tp.setTrayState("OCCUPIED");//托盘状态
		Integer TrayNumber = null;
		if (basicTray!=null) {
			TrayNumber = (basicTray.getId()+1);
		} else {
			TrayNumber = 1;
		}
		Tp.setDeliverId(deliverId);
		Tp.setDeptId(deptId);

		BigDecimal putNum = new BigDecimal(pandianJihuaDetailedParam.getTrueNum());//数量
		BigDecimal Supportvolume = new BigDecimal(bG.getGoodsSupportvolume());//托存量

		BigDecimal u = new BigDecimal(bG.getGoodsCharging());//单价
		BigDecimal w = new BigDecimal(bG.getGoodsWeight());//重量
		BigDecimal v = new BigDecimal(bG.getGoodsVolume());//体积
		BigDecimal as= new BigDecimal(0);
		
		if (putNum.subtract(Supportvolume).compareTo(as)== -1) {//判断一托是否可以装下全部
			storageStockParam.setStockWeight(putNum.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
			storageStockParam.setStockVolume(putNum.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
			storageStockParam.setStockMoney(putNum.multiply(u).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
			storageStockParam.setNum(putNum.toString());//数量
			storageStockParam.setBalenum(putNum.toString());
			storageStockParam.setCanNum(putNum.toString());

			BasicTrayParam trayParam = new BasicTrayParam();
			trayParam.setDeliverId(deliverId);
			trayParam.setDeptId(deptId);
			trayParam.setTrayState("IDLE");
			BasicTrayResult basicTrayResult = basicTrayService.findBySpec(trayParam,user.getOperateId());
			if (basicTrayResult != null) {
				storageStockParam.setTrayNumber(basicTrayResult.getTrayNumber());
				storageStockParam.setTrayId(Long.parseLong(basicTrayResult.getId().toString()));
				basicTrayResult.setTrayState("OCCUPIED");
				ToolUtil.copyProperties(basicTrayResult, trayParam);
				basicTrayService.update(trayParam);
			} else {
				Tp.setTrayNumber(trayCode+TrayNumber);
				basicTrayService.add(Tp);
				storageStockParam.setTrayNumber(trayCode+TrayNumber);//托盘编号
				BasicTrayResult basicTrayResult2 = basicTrayService.findBySpec(Tp,user.getOperateId());
				storageStockParam.setTrayId(Long.parseLong(basicTrayResult2.getId().toString()));
			}
			this.add(storageStockParam);//添加库存
			pandianJihuaDetailedParam.setTrayNumber(storageStockParam.getTrayNumber());
			pandianJihuaDetailedService.add(pandianJihuaDetailedParam);

			try {
				StorageStockResult result = this.findBySpec2(storageStockParam);
	            storageStockDetailedService.addNewDetailedResult("盘点", pandianJihuaDetailedParam.getDiskName(), "新增库存", "", result,user);
			} catch (Exception e) {
			}
		} else {//一托装不下
			//默认整托
			storageStockParam.setStockWeight(Supportvolume.multiply(w).toString());
			storageStockParam.setStockVolume(Supportvolume.multiply(v).toString());
			storageStockParam.setStockMoney(Supportvolume.multiply(u).toString());
			storageStockParam.setNum(Supportvolume.toString());//数量
			storageStockParam.setBalenum(Supportvolume.toString());
			storageStockParam.setCanNum(Supportvolume.toString());
			while (putNum.compareTo(as)==1) {
				if (putNum.subtract(Supportvolume).compareTo(as)==-1||putNum.subtract(Supportvolume).compareTo(as)==0) {
					storageStockParam.setStockWeight(putNum.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
					storageStockParam.setStockVolume(putNum.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
					storageStockParam.setStockMoney(putNum.multiply(u).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
					storageStockParam.setNum(putNum.toString());//数量
					storageStockParam.setBalenum(putNum.toString());
					storageStockParam.setCanNum(putNum.toString());
					BasicTrayParam trayParam = new BasicTrayParam();
					trayParam.setDeliverId(deliverId);
					trayParam.setDeptId(deptId);
					trayParam.setTrayState("IDLE");
					BasicTrayResult basicTrayResult = basicTrayService.findBySpec(trayParam,user.getOperateId());
					if (basicTrayResult != null) {
						storageStockParam.setTrayNumber(basicTrayResult.getTrayNumber());
						basicTrayResult.setTrayState("OCCUPIED");
						storageStockParam.setTrayId(Long.parseLong(basicTrayResult.getId().toString()));
						ToolUtil.copyProperties(basicTrayResult, trayParam);
						basicTrayService.update(trayParam);
					} else {
						Tp.setTrayNumber(trayCode+TrayNumber);
						storageStockParam.setTrayNumber(trayCode+TrayNumber);//托盘编号
						basicTrayService.add(Tp);
						BasicTrayResult basicTrayResult2 = basicTrayService.findBySpec(Tp,user.getOperateId());
						storageStockParam.setTrayId(Long.parseLong(basicTrayResult2.getId().toString()));
						TrayNumber++;
					}
					putNum = as;
				} else {
					BasicTrayParam trayParam = new BasicTrayParam();
					trayParam.setDeliverId(deliverId);
					trayParam.setDeptId(deptId);
					trayParam.setTrayState("IDLE");
					BasicTrayResult basicTrayResult = basicTrayService.findBySpec(trayParam,user.getOperateId());
					if (basicTrayResult != null) {
						storageStockParam.setTrayNumber(basicTrayResult.getTrayNumber());
						storageStockParam.setTrayId(Long.parseLong(basicTrayResult.getId().toString()));
						basicTrayResult.setTrayState("OCCUPIED");
						ToolUtil.copyProperties(basicTrayResult, trayParam);
						basicTrayService.update(trayParam);
					} else {
						Tp.setTrayNumber(trayCode+TrayNumber);
						storageStockParam.setTrayNumber(trayCode+TrayNumber);//托盘编号
						basicTrayService.add(Tp);
						BasicTrayResult basicTrayResult2 = basicTrayService.findBySpec(Tp,user.getOperateId());
						storageStockParam.setTrayId(Long.parseLong(basicTrayResult2.getId().toString()));
						TrayNumber++;
					}

					BigDecimal putNum2	=  putNum.subtract(Supportvolume);
					putNum = putNum2;

				}
				this.add(storageStockParam);//添加
				try {
					StorageStockResult result = this.findBySpec2(storageStockParam);
		            storageStockDetailedService.addNewDetailedResult("盘点", pandianJihuaDetailedParam.getDiskName(), "新增库存", "", result,user);
				} catch (Exception e) {
				}
				
				pandianJihuaDetailedParam.setTrueNum(storageStockParam.getNum());
				pandianJihuaDetailedParam.setTrueVolume(putNum.multiply(v).toString());
				pandianJihuaDetailedParam.setTrayNumber(storageStockParam.getTrayNumber());
				pandianJihuaDetailedService.add(pandianJihuaDetailedParam);
			}
		}
		PandianJihuaDetailedParam param = new PandianJihuaDetailedParam();
		param.setId(id);
		pandianJihuaDetailedService.delete(param);
	}

    @Resource
    private PandianJihuaDetailedService pandianJihuaDetailedService;

	/**
	 * 抽盘
	 * 矫正库存
	 */
	@Override
	public boolean correctNewChouPan(PandianChoupanDetailedParam moveDiskDetailedParam,User user) {
		SysSwitchParam dParam = new SysSwitchParam();
		dParam.setDeliverId(user.getDeliverId());
		dParam.setDeptId(user.getDeptId());
		dParam.setCode("correct_switch");
		SysSwitchResult dResult = sysSwitchService.findBySpec(dParam,user.getOperateId());
		if (dResult!=null) {
			if (ToolUtil.isNotEmpty(dResult.getOperation())) {
				if ("Y".equals(dResult.getOperation())) {
					if(moveDiskDetailedParam.getPanType().equals("新增")) {
						increaseNew(moveDiskDetailedParam,user);
					} else {
						BasicGoods basicGoods = basicGoodsService.getById(moveDiskDetailedParam.getGoodsId());
						StorageStockParam param = new StorageStockParam();
						param.setGoodsId(moveDiskDetailedParam.getGoodsId());
						param.setPositionNumber(moveDiskDetailedParam.getPositionNumber());
						param.setTrayNumber(moveDiskDetailedParam.getTrayNumber());
						param.setGoodsbatchs(moveDiskDetailedParam.getGoodsbatchs());
						List<StorageStockResult> list = this.findListBySpec(param,null);
						if (list.size()==0) {
							return false;
						}
						
						BigDecimal num = new BigDecimal(moveDiskDetailedParam.getNum());//库存
						
						BigDecimal sssnum = new BigDecimal(0);//校验是否发生变化
						for (StorageStockResult sss : list) {
							BigDecimal num2 = new BigDecimal(sss.getNum());
							sssnum = sssnum.add(num2);
						}
						if (num.compareTo(sssnum)!=0) {
							return false;
						}
						
						BigDecimal trueNum = new BigDecimal(moveDiskDetailedParam.getTrueNum());//实际
						BigDecimal differ = num.subtract(trueNum);//相差数
						BigDecimal decimal = trueNum.subtract(num);//相差数
						BigDecimal as = new BigDecimal(0);//0
						if (trueNum.compareTo(as)==0) {//盘0
							for (StorageStockResult result : list) {
								ToolUtil.copyProperties(result, param);
				                storageStockDetailedService.addNewDetailed("抽盘", "", "库存缺失", "", param,user);
								this.delete(param);
								
								try {
									StorageStockParam param2 = new StorageStockParam();
									param2.setTrayId(param.getTrayId());
									StorageStockResult storageStockResult = this.findBySpec(param2);
									if (storageStockResult == null) {
										BasicTrayParam basicTrayParam = new BasicTrayParam();
										basicTrayParam.setId(Integer.parseInt(param.getTrayId().toString()));
										basicTrayParam.setTrayState("IDLE");
										basicTrayService.update(basicTrayParam);
									}
								} catch (Exception e) {
								}
							}
						} else if (trueNum.compareTo(num) == -1) {//少了
							for (StorageStockResult result : list) {
								StorageStockResult r = result;
								BigDecimal nums = new BigDecimal(r.getNum());//一托数
								if (differ.compareTo(as)==0) {
									break;
								}
								if (nums.compareTo(differ)==1) {//可以减完
									BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume());
									BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());
									BigDecimal p = new BigDecimal(basicGoods.getGoodsCharging());
									BigDecimal s = nums.subtract(differ);
									r.setGoodsbatchs(moveDiskDetailedParam.getNewgoodsbatchs());
									r.setNum(s.toString());
									r.setBalenum(s.toString());
									r.setCanNum(s.toString());
									r.setStockVolume(s.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
									r.setStockWeight(s.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
									r.setStockMoney(s.multiply(p).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
									ToolUtil.copyProperties(r, param);
					                storageStockDetailedService.addNewDetailed("抽盘", "", "库存缺少", "原库存："+nums.toString(), param,user);
									this.update(param);
									break;
								} else {
									differ = differ.subtract(nums);
									ToolUtil.copyProperties(r, param);
					                storageStockDetailedService.addNewDetailed("抽盘", "", "库存缺少", "原库存："+nums.toString(), param,user);
									this.delete(param);
									
									try {
										StorageStockParam param2 = new StorageStockParam();
										param2.setTrayId(param.getTrayId());
										StorageStockResult storageStockResult = this.findBySpec(param2);
										if (storageStockResult == null) {
											BasicTrayParam basicTrayParam = new BasicTrayParam();
											basicTrayParam.setId(Integer.parseInt(param.getTrayId().toString()));
											basicTrayParam.setTrayState("IDLE");
											basicTrayService.update(basicTrayParam);
										}
									} catch (Exception e) {
									}
								}
							}
						} else {//盘盈
							BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume());
							BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());
							BigDecimal p = new BigDecimal(basicGoods.getGoodsCharging());
							StorageStockResult result = list.get(0);
							BigDecimal xt = new BigDecimal(result.getNum());
							BigDecimal nums = new BigDecimal(result.getNum());
							xt = xt.add(decimal);
							result.setGoodsbatchs(moveDiskDetailedParam.getNewgoodsbatchs());
							result.setNum(xt.toString());
							result.setBalenum(xt.toString());
							result.setCanNum(xt.toString());
							result.setStockVolume(xt.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
							result.setStockWeight(xt.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
							result.setStockMoney(xt.multiply(p).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
							ToolUtil.copyProperties(result, param);
			                storageStockDetailedService.addNewDetailed("抽盘", "", "库存多出", "原库存："+nums.toString(), param,user);
							this.update(param);
						}
					}
				}
			}
		}
		return true;
	}
	
	@Resource
	BasicAreaService basicAreaService;
	
	@Resource
	MoveDiskDetailedService moveDiskDetailedService;

    @Autowired
    private StorageStockDetailedService storageStockDetailedService;
	
	/**
	 * 库存管理
	 * 新增库存
	 * @param moveDiskDetailedParam
	 * @param user
	 */
	private void increaseNew(MoveDiskDetailedParam moveDiskDetailedParam, User user) {
		Long deliverId = user.getDeliverId();
		Long deptId = user.getDeptId();
		String trayCode = getOperateIdOrderPrefix(user)+"-";
		
		BasicGoods bG = basicGoodsService.getById(moveDiskDetailedParam.getGoodsId());//商品
		BasicWarehouse basicWarehouse = basicWarehouseService.getById(moveDiskDetailedParam.getWarehouseId());
		BasicArea basicArea = basicAreaService.getById(moveDiskDetailedParam.getAreaId());
		StorageStockParam storageStockParam = new StorageStockParam();
		storageStockParam.setOperateId(Long.parseLong(basicWarehouse.getWarehouseOperateId().toString()));
		storageStockParam.setOperateName(basicWarehouse.getWarehouseOperateName());
		storageStockParam.setCustomerId(Long.parseLong(bG.getGoodsCustomerId().toString()));
		storageStockParam.setCustomerName(bG.getGoodsCustomerName());
		storageStockParam.setWarehouseId(moveDiskDetailedParam.getWarehouseId());
		storageStockParam.setWarehouseName(basicWarehouse.getWarehouseName());
		storageStockParam.setAreaId(moveDiskDetailedParam.getAreaId());
		storageStockParam.setAreaNumber(basicArea.getAreaNumber());
		storageStockParam.setPositionId(moveDiskDetailedParam.getPositionId());
		storageStockParam.setPositionNumber(moveDiskDetailedParam.getPositionNumber());
		storageStockParam.setGoodsId(moveDiskDetailedParam.getGoodsId());
		storageStockParam.setGoodsName(moveDiskDetailedParam.getGoodsName());
		storageStockParam.setGoodsNumber(moveDiskDetailedParam.getGoodsNumber());
		storageStockParam.setProducetime(moveDiskDetailedParam.getNewgoodsbatchs());
		storageStockParam.setGoodsbatchs(moveDiskDetailedParam.getGoodsbatchs());
		storageStockParam.setPutTime(moveDiskDetailedParam.getNewgoodsbatchs());
		storageStockParam.setStockstate("in_stock");
		storageStockParam.setDeliverId(deliverId);
		storageStockParam.setDeptId(deptId);
		storageStockParam.setUnitprice(bG.getGoodsCharging());
		
		//托盘信息
		BasicTrayParam Tp = new BasicTrayParam();
		BasicTray basicTray = basicTrayService.findByThelastone();
		Tp.setTrayState("OCCUPIED");//托盘状态
		Integer TrayNumber = null;
		if (basicTray!=null) {
			TrayNumber = (basicTray.getId()+1);
		} else {
			TrayNumber = 1;
		}
		Tp.setDeliverId(deliverId);
		Tp.setDeptId(deptId);

		BigDecimal putNum = new BigDecimal(moveDiskDetailedParam.getTrueNum());//数量
		BigDecimal Supportvolume = new BigDecimal(bG.getGoodsSupportvolume());//托存量

		BigDecimal u = new BigDecimal(bG.getGoodsCharging());//单价
		BigDecimal w = new BigDecimal(bG.getGoodsWeight());//重量
		BigDecimal v = new BigDecimal(bG.getGoodsVolume());//体积
		BigDecimal as= new BigDecimal(0);
		
		if (putNum.subtract(Supportvolume).compareTo(as)== -1) {//判断一托是否可以装下全部
			storageStockParam.setStockWeight(putNum.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
			storageStockParam.setStockVolume(putNum.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
			storageStockParam.setStockMoney(putNum.multiply(u).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
			storageStockParam.setNum(putNum.toString());//数量
			storageStockParam.setBalenum(putNum.toString());
			storageStockParam.setCanNum(putNum.toString());

			BasicTrayParam trayParam = new BasicTrayParam();
			trayParam.setDeliverId(deliverId);
			trayParam.setDeptId(deptId);
			trayParam.setTrayState("IDLE");
			BasicTrayResult basicTrayResult = basicTrayService.findBySpec(trayParam,user.getOperateId());
			if (basicTrayResult != null) {
				storageStockParam.setTrayNumber(basicTrayResult.getTrayNumber());
				storageStockParam.setTrayId(Long.parseLong(basicTrayResult.getId().toString()));
				basicTrayResult.setTrayState("OCCUPIED");
				ToolUtil.copyProperties(basicTrayResult, trayParam);
				basicTrayService.update(trayParam);
			} else {
				Tp.setTrayNumber(trayCode+TrayNumber);
				basicTrayService.add(Tp);
				storageStockParam.setTrayNumber(trayCode+TrayNumber);//托盘编号
				BasicTrayResult basicTrayResult2 = basicTrayService.findBySpec(Tp,user.getOperateId());
				storageStockParam.setTrayId(Long.parseLong(basicTrayResult2.getId().toString()));
			}
			this.add(storageStockParam);//添加库存
			try {
				StorageStockResult result = this.findBySpec2(storageStockParam);
	            storageStockDetailedService.addNewDetailedResult("Inventory Management", "", "New Inventory Added", "", result,user);
			} catch (Exception e) {
			}
			moveDiskDetailedParam.setTrayNumber(storageStockParam.getTrayNumber());
            moveDiskDetailedService.add(moveDiskDetailedParam);
		} else {//一托装不下
			//默认整托
			storageStockParam.setStockWeight(Supportvolume.multiply(w).toString());
			storageStockParam.setStockVolume(Supportvolume.multiply(v).toString());
			storageStockParam.setStockMoney(Supportvolume.multiply(u).toString());
			storageStockParam.setNum(Supportvolume.toString());//数量
			storageStockParam.setBalenum(Supportvolume.toString());
			storageStockParam.setCanNum(Supportvolume.toString());
			while (putNum.compareTo(as)==1) {
				if (putNum.subtract(Supportvolume).compareTo(as)==-1||putNum.subtract(Supportvolume).compareTo(as)==0) {
					storageStockParam.setStockWeight(putNum.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
					storageStockParam.setStockVolume(putNum.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
					storageStockParam.setStockMoney(putNum.multiply(u).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
					storageStockParam.setNum(putNum.toString());//数量
					storageStockParam.setBalenum(putNum.toString());
					storageStockParam.setCanNum(putNum.toString());
					BasicTrayParam trayParam = new BasicTrayParam();
					trayParam.setDeliverId(deliverId);
					trayParam.setDeptId(deptId);
					trayParam.setTrayState("IDLE");
					BasicTrayResult basicTrayResult = basicTrayService.findBySpec(trayParam,user.getOperateId());
					if (basicTrayResult != null) {
						storageStockParam.setTrayNumber(basicTrayResult.getTrayNumber());
						basicTrayResult.setTrayState("OCCUPIED");
						storageStockParam.setTrayId(Long.parseLong(basicTrayResult.getId().toString()));
						ToolUtil.copyProperties(basicTrayResult, trayParam);
						basicTrayService.update(trayParam);
					} else {
						Tp.setTrayNumber(trayCode+TrayNumber);
						storageStockParam.setTrayNumber(trayCode+TrayNumber);//托盘编号
						basicTrayService.add(Tp);
						BasicTrayResult basicTrayResult2 = basicTrayService.findBySpec(Tp,user.getOperateId());
						storageStockParam.setTrayId(Long.parseLong(basicTrayResult2.getId().toString()));
						TrayNumber++;
					}
					putNum = as;
				} else {
					BasicTrayParam trayParam = new BasicTrayParam();
					trayParam.setDeliverId(deliverId);
					trayParam.setDeptId(deptId);
					trayParam.setTrayState("IDLE");
					BasicTrayResult basicTrayResult = basicTrayService.findBySpec(trayParam,user.getOperateId());
					if (basicTrayResult != null) {
						storageStockParam.setTrayNumber(basicTrayResult.getTrayNumber());
						storageStockParam.setTrayId(Long.parseLong(basicTrayResult.getId().toString()));
						basicTrayResult.setTrayState("OCCUPIED");
						ToolUtil.copyProperties(basicTrayResult, trayParam);
						basicTrayService.update(trayParam);
					} else {
						Tp.setTrayNumber(trayCode+TrayNumber);
						storageStockParam.setTrayNumber(trayCode+TrayNumber);//托盘编号
						basicTrayService.add(Tp);
						BasicTrayResult basicTrayResult2 = basicTrayService.findBySpec(Tp,user.getOperateId());
						storageStockParam.setTrayId(Long.parseLong(basicTrayResult2.getId().toString()));
						TrayNumber++;
					}

					BigDecimal putNum2	=  putNum.subtract(Supportvolume);
					putNum = putNum2;

				}
				this.add(storageStockParam);//添加
				try {
					StorageStockResult result = this.findBySpec2(storageStockParam);
		            storageStockDetailedService.addNewDetailedResult("Inventory Management", "", "New Inventory Added", "", result,user);
				} catch (Exception e) {
				}
				moveDiskDetailedParam.setTrueNum(storageStockParam.getNum());
				moveDiskDetailedParam.setTrayNumber(storageStockParam.getTrayNumber());
	            moveDiskDetailedService.add(moveDiskDetailedParam);
			}
		}
	}
	
	@Resource
	PandianChoupanDetailedService pandianChoupanDetailedService;
    
	/**
	 * 抽盘
	 * 新增库存
	 * @param moveDiskDetailedParam
	 * @param user
	 */
	private void increaseNew(PandianChoupanDetailedParam moveDiskDetailedParam, User user) {
		Integer id = moveDiskDetailedParam.getId();
		moveDiskDetailedParam.setId(null);
		Long deliverId = user.getDeliverId();
		Long deptId = user.getDeptId();
		String trayCode = getOperateIdOrderPrefix(user)+"-";
		
		BasicGoods bG = basicGoodsService.getById(moveDiskDetailedParam.getGoodsId());//商品
		BasicWarehouse basicWarehouse = basicWarehouseService.getById(moveDiskDetailedParam.getWarehouseId());
		BasicArea basicArea = basicAreaService.getById(moveDiskDetailedParam.getAreaId());
		StorageStockParam storageStockParam = new StorageStockParam();
		storageStockParam.setOperateId(Long.parseLong(basicWarehouse.getWarehouseOperateId().toString()));
		storageStockParam.setOperateName(basicWarehouse.getWarehouseOperateName());
		storageStockParam.setCustomerId(Long.parseLong(bG.getGoodsCustomerId().toString()));
		storageStockParam.setCustomerName(bG.getGoodsCustomerName());
		storageStockParam.setWarehouseId(moveDiskDetailedParam.getWarehouseId());
		storageStockParam.setWarehouseName(basicWarehouse.getWarehouseName());
		storageStockParam.setAreaId(moveDiskDetailedParam.getAreaId());
		storageStockParam.setAreaNumber(basicArea.getAreaNumber());
		storageStockParam.setPositionId(moveDiskDetailedParam.getPositionId());
		storageStockParam.setPositionNumber(moveDiskDetailedParam.getPositionNumber());
		storageStockParam.setGoodsId(moveDiskDetailedParam.getGoodsId());
		storageStockParam.setGoodsName(moveDiskDetailedParam.getGoodsName());
		storageStockParam.setGoodsNumber(moveDiskDetailedParam.getGoodsNumber());
		if(ToolUtil.isEmpty(moveDiskDetailedParam.getNewgoodsbatchs())) {
			storageStockParam.setProducetime(DateUtil.getDate());
		} else {
			storageStockParam.setProducetime(moveDiskDetailedParam.getNewgoodsbatchs());
		}
		if(ToolUtil.isEmpty(moveDiskDetailedParam.getGoodsbatchs())) {
			storageStockParam.setGoodsbatchs(DateUtil.getDate().replaceAll("-", ""));
		} else {
			storageStockParam.setGoodsbatchs(moveDiskDetailedParam.getGoodsbatchs());
		}
		storageStockParam.setPutTime(DateUtil.getDate());
		storageStockParam.setStockstate("IN_STOCK");
		storageStockParam.setDeliverId(deliverId);
		storageStockParam.setDeptId(deptId);
		storageStockParam.setUnitprice(bG.getGoodsCharging());
		
		//托盘信息
		BasicTrayParam Tp = new BasicTrayParam();
		BasicTray basicTray = basicTrayService.findByThelastone();
		Tp.setTrayState("OCCUPIED");//托盘状态
		Integer TrayNumber = null;
		if (basicTray!=null) {
			TrayNumber = (basicTray.getId()+1);
		} else {
			TrayNumber = 1;
		}
		Tp.setDeliverId(deliverId);
		Tp.setDeptId(deptId);

		BigDecimal putNum = new BigDecimal(moveDiskDetailedParam.getTrueNum());//数量
		BigDecimal Supportvolume = new BigDecimal(bG.getGoodsSupportvolume());//托存量

		BigDecimal u = new BigDecimal(bG.getGoodsCharging());//单价
		BigDecimal w = new BigDecimal(bG.getGoodsWeight());//重量
		BigDecimal v = new BigDecimal(bG.getGoodsVolume());//体积
		BigDecimal as= new BigDecimal(0);
		
		if (putNum.subtract(Supportvolume).compareTo(as)== -1) {//判断一托是否可以装下全部
			storageStockParam.setStockWeight(putNum.multiply(w).toString());
			storageStockParam.setStockVolume(putNum.multiply(v).toString());
			storageStockParam.setStockMoney(putNum.multiply(u).toString());
			storageStockParam.setNum(putNum.toString());//数量
			storageStockParam.setBalenum(putNum.toString());
			storageStockParam.setCanNum(putNum.toString());

			BasicTrayParam trayParam = new BasicTrayParam();
			trayParam.setDeliverId(deliverId);
			trayParam.setDeptId(deptId);
			trayParam.setTrayState("IDLE");
			BasicTrayResult basicTrayResult = basicTrayService.findBySpec(trayParam,user.getOperateId());
			if (basicTrayResult != null) {
				storageStockParam.setTrayNumber(basicTrayResult.getTrayNumber());
				storageStockParam.setTrayId(Long.parseLong(basicTrayResult.getId().toString()));
				basicTrayResult.setTrayState("OCCUPIED");
				ToolUtil.copyProperties(basicTrayResult, trayParam);
				basicTrayService.update(trayParam);
			} else {
				Tp.setTrayNumber(trayCode+TrayNumber);
				basicTrayService.add(Tp);
				storageStockParam.setTrayNumber(trayCode+TrayNumber);//托盘编号
				BasicTrayResult basicTrayResult2 = basicTrayService.findBySpec(Tp,user.getOperateId());
				storageStockParam.setTrayId(Long.parseLong(basicTrayResult2.getId().toString()));
			}
			this.add(storageStockParam);//添加
			try {
				StorageStockResult result = this.findBySpec2(storageStockParam);
	            storageStockDetailedService.addNewDetailedResult("抽盘", "", "新增库存", "", result,user);
			} catch (Exception e) {
			}
			moveDiskDetailedParam.setTrayNumber(storageStockParam.getTrayNumber());
			pandianChoupanDetailedService.add(moveDiskDetailedParam);
		} else {//一托装不下
			//默认整托
			storageStockParam.setStockWeight(Supportvolume.multiply(w).toString());
			storageStockParam.setStockVolume(Supportvolume.multiply(v).toString());
			storageStockParam.setStockMoney(Supportvolume.multiply(u).toString());
			storageStockParam.setNum(Supportvolume.toString());//数量
			storageStockParam.setBalenum(Supportvolume.toString());
			storageStockParam.setCanNum(Supportvolume.toString());
			while (putNum.compareTo(as)==1) {
				if (putNum.subtract(Supportvolume).compareTo(as)==-1||putNum.subtract(Supportvolume).compareTo(as)==0) {
					storageStockParam.setStockWeight(putNum.multiply(w).toString());
					storageStockParam.setStockVolume(putNum.multiply(v).toString());
					storageStockParam.setStockMoney(putNum.multiply(u).toString());
					storageStockParam.setNum(putNum.toString());//数量
					storageStockParam.setBalenum(putNum.toString());
					storageStockParam.setCanNum(putNum.toString());
					BasicTrayParam trayParam = new BasicTrayParam();
					trayParam.setDeliverId(deliverId);
					trayParam.setDeptId(deptId);
					trayParam.setTrayState("IDLE");
					BasicTrayResult basicTrayResult = basicTrayService.findBySpec(trayParam,user.getOperateId());
					if (basicTrayResult != null) {
						storageStockParam.setTrayNumber(basicTrayResult.getTrayNumber());
						basicTrayResult.setTrayState("OCCUPIED");
						storageStockParam.setTrayId(Long.parseLong(basicTrayResult.getId().toString()));
						ToolUtil.copyProperties(basicTrayResult, trayParam);
						basicTrayService.update(trayParam);
					} else {
						Tp.setTrayNumber(trayCode+TrayNumber);
						storageStockParam.setTrayNumber(trayCode+TrayNumber);//托盘编号
						basicTrayService.add(Tp);
						BasicTrayResult basicTrayResult2 = basicTrayService.findBySpec(Tp,user.getOperateId());
						storageStockParam.setTrayId(Long.parseLong(basicTrayResult2.getId().toString()));
						TrayNumber++;
					}
					putNum = as;
				} else {
					BasicTrayParam trayParam = new BasicTrayParam();
					trayParam.setDeliverId(deliverId);
					trayParam.setDeptId(deptId);
					trayParam.setTrayState("IDLE");
					BasicTrayResult basicTrayResult = basicTrayService.findBySpec(trayParam,user.getOperateId());
					if (basicTrayResult != null) {
						storageStockParam.setTrayNumber(basicTrayResult.getTrayNumber());
						storageStockParam.setTrayId(Long.parseLong(basicTrayResult.getId().toString()));
						basicTrayResult.setTrayState("OCCUPIED");
						ToolUtil.copyProperties(basicTrayResult, trayParam);
						basicTrayService.update(trayParam);
					} else {
						Tp.setTrayNumber(trayCode+TrayNumber);
						storageStockParam.setTrayNumber(trayCode+TrayNumber);//托盘编号
						basicTrayService.add(Tp);
						BasicTrayResult basicTrayResult2 = basicTrayService.findBySpec(Tp,user.getOperateId());
						storageStockParam.setTrayId(Long.parseLong(basicTrayResult2.getId().toString()));
						TrayNumber++;
					}

					BigDecimal putNum2	=  putNum.subtract(Supportvolume);
					putNum = putNum2;

				}
				this.add(storageStockParam);//添加
				try {
					StorageStockResult result = this.findBySpec2(storageStockParam);
		            storageStockDetailedService.addNewDetailedResult("抽盘", "", "新增库存", "", result,user);
				} catch (Exception e) {
				}
				moveDiskDetailedParam.setTrueNum(storageStockParam.getNum());
				moveDiskDetailedParam.setTrayNumber(storageStockParam.getTrayNumber());
				pandianChoupanDetailedService.add(moveDiskDetailedParam);
			}
		}
		PandianChoupanDetailedParam param = new PandianChoupanDetailedParam();
		param.setId(id);
		pandianChoupanDetailedService.delete(param);
	}

	/**
	 * 矫正库存
	 */
	@Override
	public boolean correct(MoveDiskDetailedParam moveDiskDetailedParam) {
		User user = userService.getcurrentUser();
		SysSwitchParam dParam = new SysSwitchParam();
		dParam.setDeliverId(user.getDeliverId());
		dParam.setDeptId(user.getDeptId());
		dParam.setCode("correct_switch");
		SysSwitchResult dResult = sysSwitchService.findBySpec(dParam,user.getOperateId());
		if (dResult!=null) {
			if (ToolUtil.isNotEmpty(dResult.getOperation())) {
				if ("Y".equals(dResult.getOperation())) {
					StorageStockParam param = new StorageStockParam();
					param.setGoodsId(moveDiskDetailedParam.getGoodsId());
					param.setPositionNumber(moveDiskDetailedParam.getPositionNumber());
					param.setTrayNumber(moveDiskDetailedParam.getTrayNumber());
					param.setPutTime(moveDiskDetailedParam.getGoodsbatchs());
					List<StorageStockResult> list = this.findListBySpec(param,null);
					if (list.size()==0) {
						return false;
					}

					BigDecimal num = new BigDecimal(moveDiskDetailedParam.getNum());//库存
					
					BigDecimal sssnum = new BigDecimal(0);//校验是否发生变化
					for (StorageStockResult sss : list) {
						BigDecimal num2 = new BigDecimal(sss.getNum());
						sssnum = sssnum.add(num2);
					}
					if (num.compareTo(sssnum)!=0) {
						return false;
					}
					
					BigDecimal trueNum = new BigDecimal(moveDiskDetailedParam.getTrueNum());//实际
					BigDecimal differ = num.subtract(trueNum);//相差数
					BigDecimal decimal = trueNum.subtract(num);//相差数
					BigDecimal as = new BigDecimal(0);//0
					if (trueNum.compareTo(as)==0) {//盘0
						for (StorageStockResult result : list) {
				            ToolUtil.copyProperties(result, param);
				            this.delete(param);
						}
					} else if (trueNum.compareTo(num) == -1) {//少了
						for (StorageStockResult result : list) {
							StorageStockResult r = result;
							BigDecimal nums = new BigDecimal(r.getNum());//一托数
							if (differ.compareTo(as)==0) {
								break;
							}
							if (nums.compareTo(differ)==1) {//可以减完
								BigDecimal s = nums.subtract(differ);
								r.setPutTime(moveDiskDetailedParam.getNewgoodsbatchs());
								r.setNum(s.toString());
								r.setBalenum(s.toString());
								r.setCanNum(s.toString());
					            ToolUtil.copyProperties(r, param);
					            this.update(param);
								break;
							} else {
								differ = differ.subtract(nums);
						        ToolUtil.copyProperties(r, param);
								this.delete(param);
							}
						}
					} else {//盘盈
						StorageStockResult result = list.get(0);
						BigDecimal xt = new BigDecimal(result.getNum());
						xt = xt.add(decimal);
						result.setPutTime(moveDiskDetailedParam.getNewgoodsbatchs());
						result.setNum(xt.toString());
						result.setBalenum(xt.toString());
						result.setCanNum(xt.toString());
				        ToolUtil.copyProperties(result, param);
			            this.update(param);
					}
				}
			}
		}
		return true;
	}
    
	/**
	 * 修改库位
	 */
	@Override
	@Transactional(rollbackFor = Exception.class,timeout=60)
	public String modifyStorehouse(StorageOutDetailedParam param) {
        List<StorageOutDetailed> solist = new ArrayList<StorageOutDetailed>();//要保存的 拣货单明细list
		String msg = matching2(param,solist);
		if ("n".equals(msg)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
			return msg;
		}
        if ( solist.size() > 0) {
    		storageOutDetailedService.delete(param);
        	storageOutDetailedService.saveBatchList(solist);

            //合并同一托拣货明细
    		 String[] strs2 = param.getStorageOutNumber().split(",");
    		StorageOutDetailedParam storageOutDetailedParamp = new StorageOutDetailedParam();
    		storageOutDetailedParamp.setStorageGoodsId(param.getStorageGoodsId());
            List<StorageOutDetailedResult>  list2 =  storageOutDetailedService.findgoodsbystrs(storageOutDetailedParamp,strs2);//合计明细  按库存id和订单号去重
            for (StorageOutDetailedResult r2 : list2) {
           	 if(r2.getStockId()==null) {
           		 continue;
           	 }
           	 StorageOutDetailedParam param2 = new StorageOutDetailedParam();
           	param2.setStockId(r2.getStockId());
           	param2.setStorageOutNumber(r2.getStorageOutNumber());
           	param2.setStorageGoodsId(r2.getStorageGoodsId());
            List<StorageOutDetailedResult>  list3 =  storageOutDetailedService.findListStockIdBySpec(param2);//查询是否存在多条
           	 if(list3.size()>=2) {
           		 for (int i = 0; i < list3.size(); i++) {
               		 StorageOutDetailedParam storageOutDetailedParam3 = new StorageOutDetailedParam();
               		storageOutDetailedParam3.setId(list3.get(i).getId());
               		storageOutDetailedService.delete(storageOutDetailedParam3);
    			 }
           		 StorageOutDetailedParam storageOutDetailedParam2 = new StorageOutDetailedParam();
           		 StorageOutDetailedResult storageOutDetailedResult = list3.get(0);
           		 storageOutDetailedResult.setId(null);
           		 storageOutDetailedResult.setStoragePutbalenum(r2.getStoragePutbalenum());
           		 storageOutDetailedResult.setStorageNumber(r2.getStorageNumber());
           		 storageOutDetailedResult.setStorageWeight(r2.getStorageWeight());
           		 storageOutDetailedResult.setStorageVolume(r2.getStorageVolume());
           		 storageOutDetailedResult.setStorageMoney(r2.getStorageMoney());
           		 ToolUtil.copyProperties(storageOutDetailedResult, storageOutDetailedParam2);
           		 storageOutDetailedParam2.setSigns("K");
           		 storageOutDetailedService.add(storageOutDetailedParam2);
           	 }
    		}
        }
		return "y";
	}
	
	/**
	 * 匹配库位
	 */
	private String matching2(StorageOutDetailedParam detailedParam,List<StorageOutDetailed> solist) {
		if (detailedParam==null) {
			return null;
		}
		String str = detailedParam.getStorageOutNumber();//拣货单
		String[]  strs=str.split(",");
		StorageOutResult outResult = new StorageOutResult();
		for(int i=0,len=strs.length;i<len;i++) {
			StorageOutParam outParam = new StorageOutParam();
			outParam.setStorageOutNumber(strs[i].toString());
			outResult = storageOutService.findBySpec(outParam);
		}
		
		BasicGoods basicGoods = basicGoodsService.getById(detailedParam.getStorageGoodsId());
		BasicCustomer basicCustomer = basicCustomerService.getById(basicGoods.getGoodsCustomerId());
        //出库数量
        BigDecimal outNumber = new BigDecimal(detailedParam.getStorageNumber());
        //单价
        BigDecimal u = new BigDecimal(basicGoods.getGoodsCharging());

		//查询 库存
		//规则：1.如果指定批次，优先出库   2.散托优先出库    3.批次较早，优先出库  4.批次较早的比散托的优先级高
        StorageStockParam sp = new StorageStockParam();//查询 库存单明细 where 商品,仓库id。
        
        OutOrderDetailedParam outOrderDetailedParam = new OutOrderDetailedParam();
        outOrderDetailedParam.setDetailedOutNumber(outResult.getOutOrderNumber());
        outOrderDetailedParam.setDetailedGoodsId(Long.parseLong(detailedParam.getStorageGoodsId().toString())); 
 	   OutOrderDetailedResult outOrderDetailedResult =  outOrderDetailedService.findBySpec(outOrderDetailedParam);
 	   if(outOrderDetailedResult != null) {
 		   if(ToolUtil.isNotEmpty(outOrderDetailedResult.getDetailedBatchnumber())  ) {
 			   StorageStockParam param2 = new StorageStockParam();
 			   param2.setWarehouseId(outResult.getOutStorehouseId());
 			   param2.setPositionNumber(detailedParam.getStoragePostionNumber());
 			   param2.setGoodsId(detailedParam.getStorageGoodsId());
 			   param2.setGoodsbatchs(outOrderDetailedResult.getDetailedBatchnumber());
 			   List<StorageStockResult> list = storageStockService.findListBySpec(param2,null);
 			   
 			   if (list.size()==0) {
 	    			return "n";
 			   }
			   sp.setGoodsbatchs(outOrderDetailedResult.getDetailedBatchnumber());
 		   }
 	   }
 	   
        sp.setWarehouseId(outResult.getOutStorehouseId());//仓库id
        sp.setPositionNumber(detailedParam.getStoragePostionNumber());
        sp.setGoodsId(Long.parseLong(basicGoods.getId().toString()));//商品id
        List<StorageStockResult> srl = storageStockService.finByOnlyOne(sp);
        
        int srls = 0;
        BigDecimal result = new BigDecimal(0);
        Long stockId = 0L;
        while (outNumber.compareTo(result) == 1){
        	if (srls==srl.size()||srl==null) {
        		//System.out.println("库存不足");
    			return "n";
			}
        	StorageStockResult stock = srl.get(srls);

        	StorageOutDetailed storage = new StorageOutDetailed();
			ToolUtil.copyProperties(detailedParam,storage);
			storage.setSigns("L");
            BigDecimal putNum = new BigDecimal(stock.getNum());//托盘商品数量
            if (putNum.compareTo(result) == 0) {
                srls++;
				continue;
			}
            if(!stock.getPositionNumber().equals(detailedParam.getStoragePostionNumber())) {
                srls++;
				continue;
            }

            //去除被占用的库存
            if(ToolUtil.isNotEmpty(basicCustomer.getOccupy()) && basicCustomer.getOccupy().equals("是")) {
            	StorageOutDetailedParam detailedParam2 = new StorageOutDetailedParam();
            	detailedParam2.setId(detailedParam.getId());
            	detailedParam2.setStockId(Long.parseLong(stock.getId().toString()));
            	detailedParam2.setStorageOutStatus("PENDING_PICKING");
            	StorageOutDetailedResult result2 = storageOutDetailedService.sumByStockId(detailedParam2);
            	if(result2 != null) {
            		BigDecimal rr2 = new BigDecimal(result2.getStorageNumber());
            		if(rr2.compareTo(result) == 1) {
            			if(putNum.compareTo(rr2) == 1) {
            				putNum = putNum.subtract(rr2);
            			} else {
            				srls++;
            				continue;
            			}
            		}
            	}
            } else if (ToolUtil.isNotEmpty(outResult.getMark())){//如果合单  去除被合单占用的库存
            	StorageOutDetailedParam detailedParam2 = new StorageOutDetailedParam();
            	detailedParam2.setId(detailedParam.getId());
            	detailedParam2.setStockId(Long.parseLong(stock.getId().toString()));
            	detailedParam2.setStorageOutStatus("PENDING_PICKING");
            	StorageOutDetailedResult result2 = storageOutDetailedService.sumByStockId2(detailedParam2,outResult.getMark());
            	if(result2 != null) {
            		BigDecimal rr2 = new BigDecimal(result2.getStorageNumber());
            		if(rr2.compareTo(result) == 1) {
            			if(putNum.compareTo(rr2) == 1) {
            				putNum = putNum.subtract(rr2);
            			} else {
            				srls++;
            				continue;
            			}
            		}
            	}
            } else {//去除被同一单子占用的库存
            	StorageOutDetailedParam detailedParam2 = new StorageOutDetailedParam();
            	detailedParam2.setId(detailedParam.getId());
            	detailedParam2.setStockId(Long.parseLong(stock.getId().toString()));
            	detailedParam2.setStorageOutStatus("PENDING_PICKING");
            	detailedParam2.setStorageOutNumber(detailedParam.getStorageOutNumber());
            	StorageOutDetailedResult result2 = storageOutDetailedService.sumByStockId(detailedParam2);
            	if(result2 != null) {
            		BigDecimal rr2 = new BigDecimal(result2.getStorageNumber());
            		if(rr2.compareTo(result) == 1) {
            			if(putNum.compareTo(rr2) == 1) {
            				putNum = putNum.subtract(rr2);
            			} else {
            				srls++;
            				continue;
            			}
            		}
            	}
            }
            
            //这一托可以出完
            if(outNumber.subtract(putNum).compareTo(result) == -1||outNumber.subtract(putNum).compareTo(result)== 0){
                //重量
                BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());
                //体积
                BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume());
               if (putNum.subtract(outNumber).compareTo(result) == 1){
                   stockId = Long.parseLong(stock.getId().toString());//库存id
                    
                    //完善 拣货单明细
                    storage.setTrayNumber(stock.getTrayNumber());//托盘编号
                    storage.setStorageBatchnumber(stock.getGoodsbatchs());//批次
                    storage.setStorageDate(stock.getProducetime());//生产日期
                    storage.setRecommendBatchs(stock.getPutTime());//推荐批次
                    storage.setStoragePostionNumber(stock.getPositionNumber());//库位编码
                    storage.setStorageNumber(String.valueOf(outNumber));//出库数量为拣货单数量
                    storage.setStoragePutbalenum(String.valueOf(outNumber));//出库数量为拣货单大包数
                    storage.setStorageWeight(String.valueOf(outNumber.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN)));//拣货单总重量
                    storage.setStorageVolume(String.valueOf(outNumber.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN)));//拣货单总体积
                    storage.setStorageMoney(String.valueOf(u.multiply(outNumber).setScale(3, BigDecimal.ROUND_HALF_DOWN)));
                    storage.setStockId(stockId);//库存id
                    solist.add(storage);

                    BigDecimal outNumber1	=  outNumber.subtract(putNum);
                    outNumber = outNumber1;//减 出库数量
                    srls++;
               } else {
                   stockId = Long.parseLong(stock.getId().toString());//库存id
                   //完善 拣货单明细
                   storage.setTrayNumber(stock.getTrayNumber());//托盘编号
                   storage.setStorageBatchnumber(stock.getGoodsbatchs());//批次
                   storage.setStorageDate(stock.getProducetime());//生产日期
                   storage.setRecommendBatchs(stock.getPutTime());//推荐批次
                   storage.setStoragePostionNumber(stock.getPositionNumber());//库位编码
                   storage.setStorageNumber(String.valueOf(outNumber));//出库数量为拣货单数量
                   storage.setStoragePutbalenum(String.valueOf(outNumber));//出库数量为拣货单大包数
                   storage.setStorageWeight(String.valueOf(outNumber.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN)));//拣货单总重量
                   storage.setStorageVolume(String.valueOf(outNumber.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN)));//拣货单总体积
                   storage.setStorageMoney(String.valueOf(u.multiply(outNumber).setScale(3, BigDecimal.ROUND_HALF_DOWN)));
                   storage.setStockId(stockId);//库存id
                   solist.add(storage);

                   BigDecimal outNumber1	=  outNumber.subtract(putNum);
                   outNumber = outNumber1;//减 出库数量
                   srls++;
               }
            }else{
                //重量
                BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());
                //体积
                BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume());
            	//这托出不完
                stockId = Long.parseLong(stock.getId().toString());//库存id

                BigDecimal outNumber1	=  outNumber.subtract(putNum);
                outNumber = outNumber1;//减 出库数量
                
                //完善 拣货单明细
                storage.setTrayNumber(stock.getTrayNumber());
                storage.setStorageBatchnumber(stock.getGoodsbatchs());//批次
                storage.setStorageDate(stock.getProducetime());//生产日期
                storage.setRecommendBatchs(stock.getPutTime());//推荐批次
                storage.setStoragePostionNumber(stock.getPositionNumber());
                storage.setStoragePutbalenum(putNum.toString());
                storage.setStorageNumber(putNum.toString());
                storage.setStorageWeight(String.valueOf(putNum.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN)));//拣货单总重量
                storage.setStorageVolume(String.valueOf(putNum.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN)));//拣货单总体积
                storage.setStorageMoney(String.valueOf(u.multiply(putNum).setScale(3, BigDecimal.ROUND_HALF_DOWN)));
                storage.setStockId(stockId);//库存id
                solist.add(storage);
                srls++;
            }
            stock = new StorageStockResult();
            storage = new StorageOutDetailed();
        }
		return "ok";
	}

	/**
	 * 匹配库位
	 */
	@Override
	public String matching(StorageOutDetailedParam detailedParam) {
		if (detailedParam==null) {
			return null;
		}
        List<StorageOutDetailed> solist = new ArrayList<StorageOutDetailed>();//要保存的 拣货单明细list
		String str = detailedParam.getStorageOutNumber();//拣货单
		String[]  strs=str.split(",");
		StorageOutResult outResult = new StorageOutResult();
		for(int i=0,len=strs.length;i<len;i++) {
			StorageOutParam outParam = new StorageOutParam();
			outParam.setStorageOutNumber(strs[i].toString());
			outResult = storageOutService.findBySpec(outParam);
		}
		
		BasicGoods basicGoods = basicGoodsService.getById(detailedParam.getStorageGoodsId());
		BasicCustomer basicCustomer = basicCustomerService.getById(basicGoods.getGoodsCustomerId());
        //出库数量
        BigDecimal outNumber = new BigDecimal(detailedParam.getStorageNumber());
        //单价
        BigDecimal price = new BigDecimal(basicGoods.getGoodsCharging());

		//查询 库存
		//规则：1.如果指定批次，优先出库   2.散托优先出库    3.批次较早，优先出库  4.批次较早的比散托的优先级高
        StorageStockParam sp = new StorageStockParam();//查询 库存单明细 where 商品,仓库id。

        OutOrderDetailedParam outOrderDetailedParam = new OutOrderDetailedParam();
        outOrderDetailedParam.setDetailedOutNumber(outResult.getOutOrderNumber());
        outOrderDetailedParam.setDetailedGoodsId(Long.parseLong(detailedParam.getStorageGoodsId().toString())); 
        outOrderDetailedParam.setDetailedBatchnumber(detailedParam.getStorageBatchnumber());
 	   OutOrderDetailedResult outOrderDetailedResult =  outOrderDetailedService.findBySpec(outOrderDetailedParam);
 	   if(outOrderDetailedResult == null) {
 		  outOrderDetailedParam.setDetailedBatchnumber(null);
 		  outOrderDetailedResult =  outOrderDetailedService.findBySpec(outOrderDetailedParam);
 	   }
 	   if(outOrderDetailedResult != null) {
 		   if(ToolUtil.isNotEmpty(outOrderDetailedResult.getDetailedBatchnumber())) {
			   sp.setGoodsbatchs(detailedParam.getStorageBatchnumber());
 		   }
 	   }
 	   
        sp.setWarehouseId(outResult.getOutStorehouseId());//仓库id
        sp.setPositionNumber(detailedParam.getStoragePostionNumber());
        sp.setGoodsId(Long.parseLong(basicGoods.getId().toString()));//商品id
        List<StorageStockResult> srl = storageStockService.finByOnlyOne(sp);
        
        int srls = 0;
        BigDecimal result = new BigDecimal(0);
        Long stockId = 0L;
        while (outNumber.compareTo(result) == 1){
        	if (srls==srl.size()||srl==null) {
        		//System.out.println("库存不足");
    			return "n";
			}
        	StorageStockResult stock = srl.get(srls);
        	
        	StorageOutDetailed storage = new StorageOutDetailed();
			ToolUtil.copyProperties(detailedParam,storage);
			storage.setSigns("G");
            BigDecimal putNum = new BigDecimal(stock.getNum());//托盘商品数量
            
            if (putNum.compareTo(result) == 0) {
                srls++;
				continue;
			}

            //去除被占用的库存
            if(ToolUtil.isNotEmpty(basicCustomer.getOccupy()) && basicCustomer.getOccupy().equals("是")) {
            	StorageOutDetailedParam detailedParam2 = new StorageOutDetailedParam();
            	detailedParam2.setStockId(Long.parseLong(stock.getId().toString()));
            	detailedParam2.setStorageOutStatus("PENDING_PICKING");
            	StorageOutDetailedResult result2 = storageOutDetailedService.sumByStockId(detailedParam2);
            	if(result2 != null) {
            		BigDecimal rr2 = new BigDecimal(result2.getStorageNumber());
            		if(rr2.compareTo(result) == 1) {
            			if(putNum.compareTo(rr2) == 1) {
            				putNum = putNum.subtract(rr2);
            			} else {
            				srls++;
            				continue;
            			}
            		}
            	}
            } else if (ToolUtil.isNotEmpty(outResult.getMark())){//如果合单  去除被合单占用的库存
            	StorageOutDetailedParam detailedParam2 = new StorageOutDetailedParam();
            	detailedParam2.setStockId(Long.parseLong(stock.getId().toString()));
            	detailedParam2.setStorageOutStatus("PENDING_PICKING");
            	StorageOutDetailedResult result2 = storageOutDetailedService.sumByStockId2(detailedParam2,outResult.getMark());
            	if(result2 != null) {
            		BigDecimal rr2 = new BigDecimal(result2.getStorageNumber());
            		if(rr2.compareTo(result) == 1) {
            			if(putNum.compareTo(rr2) == 1) {
            				putNum = putNum.subtract(rr2);
            			} else {
            				srls++;
            				continue;
            			}
            		}
            	}
            } else { //去除被同一个单子占用的库存
            	StorageOutDetailedParam detailedParam2 = new StorageOutDetailedParam();
            	detailedParam2.setStockId(Long.parseLong(stock.getId().toString()));
            	detailedParam2.setStorageOutStatus("PENDING_PICKING");
            	detailedParam2.setStorageOutNumber(detailedParam.getStorageOutNumber());
            	StorageOutDetailedResult result2 = storageOutDetailedService.sumByStockId(detailedParam2);
            	if(result2 != null) {
            		BigDecimal rr2 = new BigDecimal(result2.getStorageNumber());
            		if(rr2.compareTo(result) == 1) {
            			if(putNum.compareTo(rr2) == 1) {
            				putNum = putNum.subtract(rr2);
            			} else {
            				srls++;
            				continue;
            			}
            		}
            	}
            }

            //这一托可以出完
            if(outNumber.subtract(putNum).compareTo(result) == -1||outNumber.subtract(putNum).compareTo(result)== 0){
                //重量
                BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());
                //体积
                BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume());
               if (putNum.subtract(outNumber).compareTo(result) == 1){
                   stockId = Long.parseLong(stock.getId().toString());//库存id
                    
                    //完善 拣货单明细
                    storage.setTrayNumber(stock.getTrayNumber());//托盘编号
                    storage.setStorageBatchnumber(stock.getGoodsbatchs());//批次
                    storage.setStorageDate(stock.getProducetime());
                    storage.setRecommendBatchs(stock.getPutTime());
                    storage.setStoragePostionNumber(stock.getPositionNumber());//库位编码
                    storage.setStorageNumber(String.valueOf(outNumber));//出库数量为拣货单数量
                    storage.setStoragePutbalenum(String.valueOf(outNumber));//出库数量为拣货单大包数
                    storage.setStoragePrice(price.toString());
                    storage.setStorageWeight(String.valueOf(outNumber.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN)));//拣货单总重量
                    storage.setStorageVolume(String.valueOf(outNumber.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN)));//拣货单总体积
                    storage.setStorageMoney(String.valueOf(price.multiply(outNumber).setScale(3, BigDecimal.ROUND_HALF_DOWN)));
                    storage.setStockId(stockId);//库存id
                    solist.add(storage);

                    BigDecimal outNumber1	=  outNumber.subtract(putNum);
                    outNumber = outNumber1;//减 出库数量
                    srls++;
               } else {
                   stockId = Long.parseLong(stock.getId().toString());//库存id
                   //完善 拣货单明细
                   storage.setTrayNumber(stock.getTrayNumber());//托盘编号
                   storage.setStorageBatchnumber(stock.getGoodsbatchs());//批次
                   storage.setStorageDate(stock.getProducetime());
                   storage.setRecommendBatchs(stock.getPutTime());
                   storage.setStoragePostionNumber(stock.getPositionNumber());//库位编码
                   storage.setStorageNumber(String.valueOf(outNumber));//出库数量为拣货单数量
                   storage.setStoragePutbalenum(String.valueOf(outNumber));//出库数量为拣货单大包数
                   storage.setStoragePrice(price.toString());
                   storage.setStorageWeight(String.valueOf(outNumber.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN)));//拣货单总重量
                   storage.setStorageVolume(String.valueOf(outNumber.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN)));//拣货单总体积
                   storage.setStorageMoney(String.valueOf(price.multiply(outNumber).setScale(3, BigDecimal.ROUND_HALF_DOWN)));
                   storage.setStockId(stockId);//库存id
                   solist.add(storage);

                   BigDecimal outNumber1	=  outNumber.subtract(putNum);
                   outNumber = outNumber1;//减 出库数量
                   srls++;
               }
            }else{
                //重量
                BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());
                //体积
                BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume());
            	//这托出不完
                stockId = Long.parseLong(stock.getId().toString());//库存id

                BigDecimal outNumber1	=  outNumber.subtract(putNum);
                outNumber = outNumber1;//减 出库数量
                
                //完善 拣货单明细
                storage.setTrayNumber(stock.getTrayNumber());
                storage.setStorageBatchnumber(stock.getGoodsbatchs());//批次
                storage.setStorageDate(stock.getProducetime());
                storage.setRecommendBatchs(stock.getPutTime());
                storage.setStoragePostionNumber(stock.getPositionNumber());
                storage.setStoragePutbalenum(putNum.toString());
                storage.setStorageNumber(putNum.toString());
                storage.setStoragePrice(price.toString());
                storage.setStorageWeight(String.valueOf(putNum.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN)));//拣货单总重量
                storage.setStorageVolume(String.valueOf(putNum.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN)));//拣货单总体积
                storage.setStorageMoney(String.valueOf(price.multiply(putNum).setScale(3, BigDecimal.ROUND_HALF_DOWN)));
                storage.setStockId(stockId);//库存id
                solist.add(storage);
                srls++;
            }
            stock = new StorageStockResult();
            storage = new StorageOutDetailed();
        }
        if ( solist.size() > 0) {
        	storageOutDetailedService.saveBatchList(solist);

            //合并同一托拣货明细
    		 String[] strs2 = detailedParam.getStorageOutNumber().split(",");
    		StorageOutDetailedParam storageOutDetailedParamp = new StorageOutDetailedParam();
    		storageOutDetailedParamp.setStorageGoodsId(detailedParam.getStorageGoodsId());
            List<StorageOutDetailedResult>  list2 =  storageOutDetailedService.findgoodsbystrs(storageOutDetailedParamp,strs2);//合计明细  按库存id和订单号去重
            for (StorageOutDetailedResult r2 : list2) {
           	 if(r2.getStockId()==null) {
           		 continue;
           	 }
           	 StorageOutDetailedParam param2 = new StorageOutDetailedParam();
           	param2.setStockId(r2.getStockId());
           	param2.setStorageOutNumber(r2.getStorageOutNumber());
           	param2.setStorageGoodsId(r2.getStorageGoodsId());
            List<StorageOutDetailedResult>  list3 =  storageOutDetailedService.findListStockIdBySpec(param2);//查询是否存在多条
	       	 if(list3.size()>=2) {
	       		 for (int i = 0; i < list3.size(); i++) {
		           		StorageOutDetailedParam storageOutDetailedParam3 = new StorageOutDetailedParam();
		           		storageOutDetailedParam3.setId(list3.get(i).getId());
		           		storageOutDetailedService.delete(storageOutDetailedParam3);
				}
	       		 StorageOutDetailedParam storageOutDetailedParam2 = new StorageOutDetailedParam();
	       		 StorageOutDetailedResult storageOutDetailedResult = list3.get(0);
	       		 storageOutDetailedResult.setId(null);
	       		 storageOutDetailedResult.setStoragePutbalenum(r2.getStoragePutbalenum());
	       		 storageOutDetailedResult.setStorageNumber(r2.getStorageNumber());
	       		 storageOutDetailedResult.setStorageWeight(r2.getStorageWeight());
	       		 storageOutDetailedResult.setStorageVolume(r2.getStorageVolume());
	       		 storageOutDetailedResult.setStorageMoney(r2.getStorageMoney());
	       		 ToolUtil.copyProperties(storageOutDetailedResult, storageOutDetailedParam2);
	       		storageOutDetailedParam2.setSigns("H");
	       		storageOutDetailedService.add(storageOutDetailedParam2);
	       	 }
    		}
        }
		return "ok";
	}

	@Override
	public List<StorageStockResult> findListBySpecandssss(StorageStockParam param) {
		return this.baseMapper.findListBySpecandssss(param);
	}

	@Override
	public StorageStockResult sumbysqzkk(StorageStockParam param) {
		return this.baseMapper.sumbysqzkk(param);
	}

	private static String getCellValue(Cell cell) {
		if (cell == null) {
			return "";
		}
		if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
			if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
				return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
			} else {
				return new BigDecimal(cell.getNumericCellValue()).toString();
			}
		} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
			return StringUtils.trimToEmpty(cell.getStringCellValue());
		} else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
			return StringUtils.trimToEmpty(cell.getCellFormula());
		} else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
			return "";
		} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
			return String.valueOf(cell.getBooleanCellValue());
		} else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
			return "ERROR";
		} else {
			return cell.toString().trim();
		}
	}

	/***
	 *处理期初库存导入
	 * @param fileName
	 * @param file
	 * @param storageStockParam
	 * @param data
	 * @return
	 * @throws IOException
	 */
	@Transactional(rollbackFor = Exception.class,timeout=100)
	@Override
	public ResponseData batchImport(String fileName, MultipartFile file, StorageStockParam storageStockParam, ResponseData data) throws IOException {
		List<StorageStockParam> storageList = new ArrayList<StorageStockParam>();
		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			data.setMessage("Incorrect upload file format");
			data.setSuccess(false);
		}
		boolean isExcel2003 = true;
		if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
			isExcel2003 = false;
		}
		InputStream is = file.getInputStream();
		Workbook wb = null;
		if (isExcel2003) {
			wb = new HSSFWorkbook(is);
		} else {
			wb = new XSSFWorkbook(is);
		}

		BasicCustomer basicCustomer = basicCustomerService.getById(storageStockParam.getCustomerId());//客户信息
		BasicOperate basicOperate = basicOperateService.getById(storageStockParam.getOperateId());//分公司信息
		BigDecimal as = new BigDecimal("0");
		User user = userService.getcurrentUser();
		String trayCode = getOperateIdOrderPrefix(user)+"-";
		Sheet sheet = wb.getSheetAt(0);
		for (int i = 1;i<sheet.getLastRowNum()+1; i++) {
			Row row = sheet.getRow(i);
			if (row == null){
				continue;
			}
			StorageStockParam stockParam = new StorageStockParam();

			String  goodsNumber = getCellValue(row.getCell(0));
			if (ToolUtil.isNotEmpty(goodsNumber)) {
				stockParam.setGoodsNumber(goodsNumber);//商品编号
			} else {
				break;
			}
			BasicGoodsParam basicGoodsParam = new BasicGoodsParam();
			basicGoodsParam.setGoodsNumber(goodsNumber);
			basicGoodsParam.setDeliverId(user.getDeliverId());
			basicGoodsParam.setDeptId(user.getDeptId());
			basicGoodsParam.setGoodsCustomerId(Integer.parseInt(storageStockParam.getCustomerId().toString()));
			BasicGoodsResult basicGoodsResult = basicGoodsService.findBySpec(basicGoodsParam,user.getOperateId());
			if(basicGoodsResult != null) {
				basicGoodsParam.setId(basicGoodsResult.getId());		
			} 

			String  GoodsName = getCellValue(row.getCell(1));
			if (ToolUtil.isNotEmpty(GoodsName)) {
				stockParam.setGoodsName(GoodsName);//商品名称
			} else {
				if(basicGoodsResult == null) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
					data.setSuccess(false);
					data.setMessage(goodsNumber+"Product name cannot be empty");
					return data;
				} else {
					stockParam.setGoodsName(basicGoodsResult.getGoodsName());//商品名称
				}
			}

			String  batch = getCellValue(row.getCell(2));//20210526
			if (ToolUtil.isNotEmpty(batch)) {
				stockParam.setGoodsbatchs(batch);//批次
				char[] dataArray = batch.toCharArray();
				StringBuffer strBuffer = new StringBuffer();
				for(int ii = 0; ii < dataArray.length; ii++){
					strBuffer.append(dataArray[ii]);
					if(ii == 3 || ii == 5){
						strBuffer.append("-");
					}
				}
				stockParam.setProducetime(strBuffer.toString());//生产日期
			} else {
				stockParam.setProducetime(getDatesssss());//生产日期
				stockParam.setGoodsbatchs(getDatesssss().replaceAll("-", ""));//批次
			}

			String  batchs = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(3));//20210526
			if (ToolUtil.isNotEmpty(batchs)) {
				char[] dataArray = batchs.toCharArray();
				StringBuffer strBuffer = new StringBuffer();
				for(int ii = 0; ii < dataArray.length; ii++){
				strBuffer.append(dataArray[ii]);
					if(ii == 3 || ii == 5){
						strBuffer.append("-");
					}
				}
				stockParam.setProducetime(strBuffer.toString());//生产日期
				if(ToolUtil.isEmpty(stockParam.getGoodsbatchs())) {
					stockParam.setGoodsbatchs(batchs);//批次
				}
			} else {
				stockParam.setProducetime(getDatesssss());//生产日期
				stockParam.setGoodsbatchs(getDatesssss().replaceAll("-", ""));//批次
			}
			
			String  putbatch = getCellValue(row.getCell(4));//20210526
			if (ToolUtil.isNotEmpty(putbatch)) {
				char[] dataArray = putbatch.toCharArray();
				StringBuffer strBuffer = new StringBuffer();
				for(int ii = 0; ii < dataArray.length; ii++){
				strBuffer.append(dataArray[ii]);
					if(ii == 3 || ii == 5){
					strBuffer.append("-");
					}
				}
				stockParam.setPutTime(strBuffer.toString());//入库批次
			} else {
				stockParam.setPutTime(getDatesssss());//入库批次
			}

			String  num = getCellValue(row.getCell(5));
			if (ToolUtil.isNotEmpty(num)) {
				BigDecimal numb = new BigDecimal(num).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				if(numb.compareTo(as) != 1) {
					continue;
				}
				stockParam.setNum(numb.toString());//数量
				stockParam.setBalenum(numb.toString());
				stockParam.setCanNum(numb.toString());
			} else {
				data.setSuccess(false);
				data.setMessage("Quantity cannot be empty!");
				return data;
			}

			String  positionNumber = getCellValue(row.getCell(6));
			if (ToolUtil.isNotEmpty(positionNumber)) {
				stockParam.setPositionNumber(positionNumber);//库位
			} else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Location No. cannot be empty!");
				return data;
			}

			String  volume = getCellValue(row.getCell(7));
			if (ToolUtil.isNotEmpty(volume)) {
				BigDecimal volumeb = new BigDecimal(volume).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				stockParam.setStockVolume(volumeb.toString());//体积
			} else {
				if (basicGoodsResult != null) {
					if (ToolUtil.isNotEmpty(basicGoodsResult.getGoodsVolume())) {
						BigDecimal gv = new BigDecimal(basicGoodsResult.getGoodsVolume());
						BigDecimal n = new BigDecimal(num).setScale(3, BigDecimal.ROUND_HALF_DOWN);
						stockParam.setStockVolume(gv.multiply(n).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//体积
					} else {
						stockParam.setStockVolume("0.1");//体积
					}
				} else {
					stockParam.setStockVolume("0.1");//体积
				}
			}

			String  stockMoney = getCellValue(row.getCell(8));
			if (ToolUtil.isNotEmpty(stockMoney)) {
				BigDecimal stockMoneyb = new BigDecimal(stockMoney).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				stockParam.setStockMoney(stockMoneyb.toString());//金额
			} else {
				BigDecimal n = new BigDecimal(num).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				if (basicGoodsResult != null) {
					if (ToolUtil.isNotEmpty(basicGoodsResult.getGoodsCharging())) {
						BigDecimal gp = new BigDecimal(basicGoodsResult.getGoodsCharging());
						stockParam.setStockMoney(gp.multiply(n).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
					} else {
						stockParam.setStockMoney(n.toString());
					}
				} else {
					stockParam.setStockMoney(n.toString());
				}
			}

			String  stockWeight = getCellValue(row.getCell(9));
			if (ToolUtil.isNotEmpty(stockWeight)) {
				BigDecimal stockWeightb = new BigDecimal(stockWeight).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				stockParam.setStockWeight(stockWeightb.toString());//重量
			} else {
				if (basicGoodsResult != null) {
					if (ToolUtil.isNotEmpty(basicGoodsResult.getGoodsWeight())) {
						BigDecimal gw = new BigDecimal(basicGoodsResult.getGoodsWeight());
						BigDecimal n = new BigDecimal(num).setScale(3, BigDecimal.ROUND_HALF_DOWN);
						stockParam.setStockWeight(gw.multiply(n).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
					} else {
						stockParam.setStockWeight("0.1");
					}
				} else {
					stockParam.setStockWeight("0.1");
				}
			}

			String  unitprice = getCellValue(row.getCell(10));
			if (ToolUtil.isNotEmpty(unitprice)) {
				BigDecimal unitpriceb = new BigDecimal(unitprice).setScale(3, BigDecimal.ROUND_HALF_DOWN);
				stockParam.setUnitprice(unitpriceb.toString());//单价
			} else {
				if (basicGoodsResult != null) {
					if (ToolUtil.isNotEmpty(basicGoodsResult.getGoodsCharging())) {
						stockParam.setUnitprice(basicGoodsResult.getGoodsCharging());
					} else {
						stockParam.setUnitprice("10");//单价
					}
				} else {
					stockParam.setUnitprice("10");//单价
				}
			}

			BasicTrayParam Tp = new BasicTrayParam();
			BasicTray basicTray = basicTrayService.findByThelastone();
			Tp.setTrayState("OCCUPIED");//托盘状态
			int TrayNumber = 0;
			if (basicTray!=null) {
				TrayNumber = (basicTray.getId()+1);
			} else {
				TrayNumber = 1;
			}
			Tp.setDeliverId(user.getDeliverId());
			Tp.setDeptId(user.getDeptId());
			
			BasicTrayParam trayParam = new BasicTrayParam();
			trayParam.setDeliverId(user.getDeliverId());
			trayParam.setDeptId(user.getDeptId());
			trayParam.setTrayState("IDLE");
			BasicTrayResult basicTrayResult = basicTrayService.findBySpec(trayParam,user.getOperateId());
			if (basicTrayResult != null) {
				stockParam.setTrayNumber(basicTrayResult.getTrayNumber());
				stockParam.setTrayId(Long.parseLong(basicTrayResult.getId().toString()));
				basicTrayResult.setTrayState("OCCUPIED");
				ToolUtil.copyProperties(basicTrayResult, trayParam);
				basicTrayService.update(trayParam);
			} else {
				Tp.setTrayNumber(trayCode+TrayNumber);
				basicTrayService.add(Tp);
				trayParam.setTrayNumber(trayCode+TrayNumber);
				trayParam.setTrayState("OCCUPIED");
				basicTrayResult = basicTrayService.findBySpec(trayParam,user.getOperateId());
				stockParam.setTrayNumber(trayCode+TrayNumber);//托盘编号
				stockParam.setTrayId(Long.parseLong(basicTrayResult.getId().toString()));
			}
			
			stockParam.setDeptId(user.getDeptId());//部门id
			stockParam.setDeliverId(user.getDeliverId());//交付id
			stockParam.setStockstate("IN_STOCK");
			
			stockParam.setOperateId(Long.valueOf(basicOperate.getId()));//分公司id
			stockParam.setOperateName(basicOperate.getOperateName());//分公司名称
			
			stockParam.setCustomerId(Long.valueOf(basicCustomer.getId()));//客户id
			stockParam.setCustomerName(basicCustomer.getCustomerName());//客户名称
			
			if (basicGoodsResult == null) {
				basicGoodsParam.setGoodsCustomerName(basicCustomer.getCustomerName());
				basicGoodsParam.setGoodsName(stockParam.getGoodsName());
				basicGoodsParam.setGoodsWeight("0.1");
				if (ToolUtil.isNotEmpty(volume)) {
					BigDecimal vv = new BigDecimal(volume);
					BigDecimal n = new BigDecimal(num);
					BigDecimal GoodsVolume = vv.divide(n,4,BigDecimal.ROUND_HALF_DOWN);
					if (GoodsVolume.compareTo(as)==1) {
						basicGoodsParam.setGoodsVolume(GoodsVolume.toString());
					} else {
						basicGoodsParam.setGoodsVolume("0.1");
					}
				} else {
					basicGoodsParam.setGoodsVolume("0.1");
				}
				basicGoodsParam.setGoodsCharging("10");
				basicGoodsParam.setGoodsBottom("10");//底
				basicGoodsParam.setGoodsLamination("10");//叠层
				basicGoodsParam.setGoodsSupportvolume("100");
				basicGoodsParam.setGoodsWarranty("36");
				basicGoodsParam.setGoodsTraylayer("1");
				basicGoodsParam.setCreateTime(new Date());
				basicGoodsService.addReturnId(basicGoodsParam);
			} 
			
			stockParam.setGoodsId(Long.valueOf(basicGoodsParam.getId()));//商品id
			
			BasicPositionParam basicPositionParam = new BasicPositionParam();
			basicPositionParam.setPositionNumber(positionNumber);
			basicPositionParam.setWarehouseId(Integer.parseInt(storageStockParam.getWarehouseId().toString()));
			basicPositionParam.setDeliverId(user.getDeliverId());
			BasicPositionResult basicPositionResult = basicPositionService.findBySpec(basicPositionParam,user.getDeptId(),user.getOperateId());
			if (basicPositionResult == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Location: " + positionNumber + " does not exist!");
				return data;
			}
			
			stockParam.setWarehouseId(Long.valueOf(basicPositionResult.getWarehouseId()));//仓库id
			stockParam.setWarehouseName(basicPositionResult.getWarehouseName());//仓库名称
			
			stockParam.setAreaId(Long.valueOf(basicPositionResult.getPositionAreaId()));//库区id
			stockParam.setAreaNumber(basicPositionResult.getAreaNumber());//库区编号
			
			stockParam.setPositionId(Long.valueOf(basicPositionResult.getId()));//库位id
			storageList.add(stockParam);
		}
		if (storageList.size() > 0){
			storageStockService.batchAddList(storageList);
		}
		data.setSuccess(true);
		return data;
	}

	@Override
	public List<StorageStockResult> moveDiskFindGoodsList(StorageStockParam param,Long operateId) {
		return this.baseMapper.moveDiskFindGoodsList(param,operateId);
	}

	@Override
	public List<StorageStockResult> findGoodsProportionNew(StorageStockParam param,Long operateId) {
		return this.baseMapper.findGoodsProportionNew(param,operateId);
	}

	@Override
	public List<StorageStockResult> findGoodsListBySpecNew(StorageStockParam param,Long operateId) {
		return this.baseMapper.findGoodsListBySpecNew(param,operateId);
	}

	@Override
	public List<StorageStockResult> findGoodsListBySpecmsNew(StorageStockParam param,Long operateId) {
		return this.baseMapper.findGoodsListBySpecmsNew(param,operateId);
	}

	@Override
	public List<StorageStockResult> moveQueryGoodsNEW(StorageStockParam param) {
		return this.baseMapper.moveQueryGoodsNEW(param);
	}

	@Override
	public List<StorageStockResult> sumGoods(StorageStockParam param) {
		return this.baseMapper.sumGoods(param);
	}

	@Override
	public StorageStockResult sumGoodsZongliang(StorageStockParam param) {
		return this.baseMapper.sumGoodsZongliang(param);
	}

	@Override
	public Integer baozhiqiCount(StorageStockParam param) {
		return this.baseMapper.baozhiqiCount(param);
	}

	@Override
	public Integer baozhiqi2Count(StorageStockParam param) {
		return this.baseMapper.baozhiqi2Count(param);
	}

	@Override
	public Integer baozhiqi1Count(StorageStockParam param) {
		return this.baseMapper.baozhiqi1Count(param);
	}

	@Override
	public Integer baozhiqiGuoqiCount(StorageStockParam param) {
		return this.baseMapper.baozhiqiGuoqiCount(param);
	}

	@Override
	public LayuiPageInfo findStockPageBySpecGoods(StorageStockParam storageStockParam,Long operateId) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.findStockPageBySpecGoods(pageContext, storageStockParam, operateId);
        return LayuiPageFactory.createPageInfo(page);
	}

	@Override
	public LayuiPageInfo findStockPageBySpecProducetime(StorageStockParam storageStockParam,Long operateId) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.findStockPageBySpecProducetime(pageContext, storageStockParam, operateId);
        return LayuiPageFactory.createPageInfo(page);
	}

	@Override
	public List<StorageStockResult> findshishikucun(StorageStockParam storageStockParam,String currentDate,Long operateId) {
        return this.baseMapper.findshishikucun(storageStockParam,currentDate, operateId);
	}

	@Override
	public List<Kfgoods> findkfgoods(StorageStockParam storageStockParam) {
		return this.baseMapper.findkfgoods(storageStockParam);
	}

	@Override
	public List<StorageStockResult> findListBySpec2(StorageStockParam storageStockParam,Long operateId) {
		return this.baseMapper.findListBySpec2(storageStockParam,operateId);
	}

	@Override
	public StorageStockResult findBySpec2(StorageStockParam sparam3) {
		return this.baseMapper.findBySpec2(sparam3);
	}

	@Override
	public StorageStockResult findDongzuoByPositionId(StorageStockParam storageStockParam) {
		return this.baseMapper.findDongzuoByPositionId(storageStockParam);
	}

	@Override
	public List<StorageStockResult> findPanDianPositionListBySpec(StorageStockParam storageStockParam, Long userId,
			Long diskId) {
		return this.baseMapper.findPanDianPositionListBySpec(storageStockParam,userId,diskId);
	}

	@Override
	public StorageStockResult findPanDianPositionBySpec(StorageStockParam storageStockParam, Long userId, Long diskId) {
		return this.baseMapper.findPanDianPositionBySpec(storageStockParam,userId,diskId);
	}

	@Override
	public List<StorageStockResult> findPanDianTrayListBySpec(StorageStockParam storageStockParam, Long userId,
			Long diskId) {
		return this.baseMapper.findPanDianTrayListBySpec(storageStockParam,userId,diskId);
	}

	@Override
	public List<StorageStockResult> findPanDianGoodsListBySpec(StorageStockParam storageStockParam, Long userId,
			Long diskId) {
		return this.baseMapper.findPanDianGoodsListBySpec(storageStockParam,userId,diskId);
	}

	@Override
	public List<StorageStockResult> moveDiskFindGoodsListChoupan(StorageStockParam storageStockParam, Long diskId,Long operateId) {
		return this.baseMapper.moveDiskFindGoodsListChoupan(storageStockParam,diskId,operateId);
	}

	@Override
	public List<StorageStockResult> findListBySpecDongzuo(StorageStockParam ssp,Long operateId) {
		return this.baseMapper.findListBySpecDongzuo(ssp,operateId);
	}

	@Override
	public LayuiPageInfo findStockPageBySpecGoodsChuzhi(StorageStockParam storageStockParam,Long operateId) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.findStockPageBySpecGoodsChuzhi(pageContext, storageStockParam, operateId);
        return LayuiPageFactory.createPageInfo(page);
	}

	@Override
	public List<StorageStockResult> findListGroupgoodsbatchs(StorageStockParam sp) {
		return this.baseMapper.findListGroupgoodsbatchs(sp);
	}

    @Resource
    private StoragePeriodService storagePeriodService;

    @Resource
    private StoragePutSingleService storagePutSingleService;

	@Override
    @Transactional(rollbackFor = Exception.class)
	public void taskJob() {
		StorageStockParam param = new StorageStockParam();
		List<StorageStockResult> list = this.baseMapper.findListSumBySpec(param);//查询当日库存合计
		for (StorageStockResult r : list) {
			StoragePeriodParam periodParam = new StoragePeriodParam();
			periodParam.setOperateId(r.getOperateId());
			periodParam.setOperateName(r.getOperateName());
			periodParam.setCustomerId(r.getCustomerId());
			periodParam.setCustomerName(r.getCustomerName());
			periodParam.setWarehouseId(r.getWarehouseId());
			periodParam.setWarehouseName(r.getWarehouseName());
			periodParam.setDates(DateUtil.getDate());
			
			periodParam.setQcNum(r.getNum());
			periodParam.setQcVolume(r.getStockVolume());
			periodParam.setQcWeight(r.getStockWeight());
			periodParam.setQcMoney(r.getStockMoney());
			
			periodParam.setDeptId(r.getDeptId());
			periodParam.setDeliverId(r.getDeliverId());
			storagePeriodService.add(periodParam);//新增当日期初库存

			StoragePeriodParam periodParam2 = new StoragePeriodParam();
			periodParam2.setCustomerId(r.getCustomerId());
			periodParam2.setWarehouseId(r.getWarehouseId());
			periodParam2.setDates(DateUtil.getPastDate(1));
			StoragePeriodResult periodResult = storagePeriodService.findBySpec(periodParam2);//上一天期间库容
			if(periodResult != null) {
				StorageStockParam param2 = new StorageStockParam();
				param2.setWarehouseId(r.getWarehouseId());
				param2.setCustomerId(r.getCustomerId());
				StorageStockResult kwshu = storageStockService.findKwShuBySpec(param2);//查询 已使用库位数
				if(kwshu != null) {
					periodResult.setKwshu(kwshu.getKwshu());
				} else {
					periodResult.setKwshu("0");
				}
				
				StoragePutSingleParam putSingleParam = new StoragePutSingleParam();
				putSingleParam.setRecommend(DateUtil.getPastDate(1));
				StoragePutSingleResult singleResult = storagePutSingleService.sumPutByDay(putSingleParam,r.getCustomerId(),r.getWarehouseId());//入库
				if(singleResult != null) {
					periodResult.setPutNum(singleResult.getRealNum());
					periodResult.setPutVolume(singleResult.getDetailedPutvolume());
					periodResult.setPutWeight(singleResult.getPutWeight());
					periodResult.setPutMoney(singleResult.getSingleMoney());
				} else {
					periodResult.setPutNum("0");
					periodResult.setPutVolume("0");
					periodResult.setPutWeight("0");
					periodResult.setPutMoney("0");
				}
				
				StorageOutDetailedParam outDetailedParam = new StorageOutDetailedParam();
				outDetailedParam.setRecommendBatchs(DateUtil.getPastDate(1));
				StorageOutDetailedResult outDetailedResult = storageOutDetailedService.sumOutByDay(outDetailedParam,r.getCustomerId(),r.getWarehouseId());//出库
				if(outDetailedResult != null) {
					periodResult.setOutNum(outDetailedResult.getRealNum());
					periodResult.setOutVolume(outDetailedResult.getStorageVolume());
					periodResult.setOutWeight(outDetailedResult.getStorageWeight());
					periodResult.setOutMoney(outDetailedResult.getStorageMoney());
				} else {
					periodResult.setOutNum("0");
					periodResult.setOutVolume("0");
					periodResult.setOutWeight("0");
					periodResult.setOutMoney("0");
				}

				periodResult.setQmNum(r.getNum());
				periodResult.setQmVolume(r.getStockVolume());
				periodResult.setQmWeight(r.getStockWeight());
				periodResult.setQmMoney(r.getStockMoney());
				ToolUtil.copyProperties(periodResult, periodParam2);
				storagePeriodService.update(periodParam2);
			}
		}
	}

	@Override
	public List<StorageStockResult> findListSumBySpec(StorageStockParam sp) {
		return this.baseMapper.findListSumBySpec(sp);
	}

	@Override
	public Integer addReturnId(StorageStockParam param) {
		return this.baseMapper.addReturnId(param);
	}

	@Resource 
	private OrderPutDetailedService orderPutDetailedService;
	
	@Override
	@Transactional(rollbackFor = Exception.class,timeout=50)
	public ResponseData putStridesAddStorageStock(OrderPut orderPut) {
		User user = userService.getcurrentUser();
		Long deliverId = user.getDeliverId();
		Long deptId = user.getDeptId();
		String trayCode = getOperateIdOrderPrefix(user)+"-";

		//托盘信息
		BasicTrayParam Tp = new BasicTrayParam();
		BasicTray basicTray = basicTrayService.findByThelastone();
		Tp.setTrayState("OCCUPIED");//托盘状态
		int TrayNumber = 0;
		if (basicTray!=null) {
			TrayNumber = (basicTray.getId()+1);
		} else {
			TrayNumber = 1;
		}
		Tp.setDeliverId(deliverId);
		Tp.setDeptId(deptId);
		
		BasicWarehouse basicWarehouse = basicWarehouseService.getById(orderPut.getWarehouseId());
		BasicPositionParam BasicPositionParam = new BasicPositionParam();
		BasicPositionParam.setWarehouseId(basicWarehouse.getId());
		BasicPositionResult basicPositionResult = basicPositionService.findBySpec(BasicPositionParam,deptId,user.getOperateId());
		if(basicPositionResult == null) {
			return ResponseData.error("No storage location found!");
		}
		
		OrderPutDetailedParam putDetailedParam = new OrderPutDetailedParam();
		putDetailedParam.setPutDetailedNumber(orderPut.getPutNumber());
		List<OrderPutDetailedResult> putDlist = orderPutDetailedService.totalListByGandPSpec(putDetailedParam);//入库订单明细
		for (OrderPutDetailedResult PutD : putDlist) {
			BasicGoods bG = basicGoodsService.getById(PutD.getDetailedGoodsnum());//商品
			BigDecimal detailedPutnum = new BigDecimal(PutD.getDetailedPutnum());//入库数量
			BigDecimal Supportvolume = new BigDecimal(bG.getGoodsSupportvolume());//每托存量
			BigDecimal w = new BigDecimal(bG.getGoodsWeight());//重量
			BigDecimal v = new BigDecimal(bG.getGoodsVolume());//体积
			BigDecimal u = new BigDecimal(bG.getGoodsCharging());//单价compareTo
			BigDecimal as = new BigDecimal(0);

			if (detailedPutnum.subtract(Supportvolume).compareTo(as)== -1) {//判断一托是否可以装下全部
				StorageStockParam param = new StorageStockParam();
				param.setOperateId(Long.parseLong(basicWarehouse.getWarehouseOperateId().toString()));
				param.setOperateName(basicWarehouse.getWarehouseOperateName());
				param.setCustomerId(orderPut.getPutCustomerId());
				param.setCustomerName(orderPut.getPutCustomerName());
				param.setWarehouseId(orderPut.getWarehouseId());
				param.setWarehouseName(orderPut.getWarehouseName());
				param.setAreaId(Long.parseLong(basicPositionResult.getPositionAreaId().toString()));
				param.setAreaNumber(basicPositionResult.getAreaNumber());
				param.setPositionId(Long.parseLong(basicPositionResult.getId().toString()));
				param.setPositionNumber(basicPositionResult.getPositionNumber());
				param.setGoodsId(PutD.getDetailedGoodsnum());
				param.setGoodsNumber(PutD.getGoodsNumber());
				param.setGoodsName(PutD.getDetailedGoodsname());
				param.setProducetime(PutD.getDetailedDateofmanufacture());
				param.setGoodsbatchs(PutD.getDetailedBatchnumber());
				param.setPutTime(PutD.getRecommend());
				param.setStockstate("IN_STOCK");
				param.setDeptId(deptId);
				param.setDeliverId(deliverId);
				param.setCreateTime(new Date());
				
				BasicTrayParam trayParam = new BasicTrayParam();
				trayParam.setDeliverId(deliverId);
				trayParam.setDeptId(deptId);
				trayParam.setTrayState("IDLE");
				BasicTrayResult basicTrayResult = basicTrayService.findBySpec(trayParam,user.getOperateId());
				if (basicTrayResult != null) {
					param.setTrayNumber(basicTrayResult.getTrayNumber());
					basicTrayResult.setTrayState("OCCUPIED");
					ToolUtil.copyProperties(basicTrayResult, trayParam);
					basicTrayService.update(trayParam);
				} else {
					Tp.setTrayNumber(trayCode+TrayNumber);
					basicTrayService.add(Tp);
					param.setTrayNumber(trayCode+TrayNumber);//托盘编号
				}
				param.setNum(detailedPutnum.toString());
				param.setBalenum(detailedPutnum.toString());
				param.setCanNum(detailedPutnum.toString());
				param.setStockWeight(w.multiply(detailedPutnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
				param.setStockVolume(v.multiply(detailedPutnum).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
				param.setUnitprice(u.toString());
				param.setStockMoney(u.multiply(detailedPutnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
				this.add(param);
				TrayNumber++;
			} else {
				List<StorageStockParam> ssPlist = new ArrayList<StorageStockParam>();//库存list
				List<BasicTray> tList = new ArrayList<BasicTray>();
				BasicTray bTray = new BasicTray();
				StorageStockParam param = new StorageStockParam();
				while (detailedPutnum.compareTo(as)==1) {
					if (detailedPutnum.subtract(Supportvolume).compareTo(as)== -1||detailedPutnum.subtract(Supportvolume).compareTo(as)== 0) {
						param.setOperateId(Long.parseLong(basicWarehouse.getWarehouseOperateId().toString()));
						param.setOperateName(basicWarehouse.getWarehouseOperateName());
						param.setCustomerId(orderPut.getPutCustomerId());
						param.setCustomerName(orderPut.getPutCustomerName());
						param.setWarehouseId(orderPut.getWarehouseId());
						param.setWarehouseName(orderPut.getWarehouseName());
						param.setAreaId(Long.parseLong(basicPositionResult.getPositionAreaId().toString()));
						param.setAreaNumber(basicPositionResult.getAreaNumber());
						param.setPositionId(Long.parseLong(basicPositionResult.getId().toString()));
						param.setPositionNumber(basicPositionResult.getPositionNumber());
						param.setGoodsId(PutD.getDetailedGoodsnum());
						param.setGoodsNumber(PutD.getGoodsNumber());
						param.setGoodsName(PutD.getDetailedGoodsname());
						param.setProducetime(PutD.getDetailedDateofmanufacture());
						param.setGoodsbatchs(PutD.getDetailedBatchnumber());
						param.setPutTime(PutD.getRecommend());
						param.setStockstate("IN_STOCK");
						param.setDeptId(deptId);
						param.setDeliverId(deliverId);
						param.setCreateTime(new Date());

						BasicTrayParam trayParam = new BasicTrayParam();
						trayParam.setDeliverId(deliverId);
						trayParam.setDeptId(deptId);
						trayParam.setTrayState("IDLE");
						BasicTrayResult basicTrayResult = basicTrayService.findBySpec(trayParam,user.getOperateId());
						if (basicTrayResult != null) {
							param.setTrayNumber(basicTrayResult.getTrayNumber());
							basicTrayResult.setTrayState("OCCUPIED");
							ToolUtil.copyProperties(basicTrayResult, trayParam);
							basicTrayService.update(trayParam);
						} else {
							Tp.setTrayNumber(trayCode+TrayNumber);
							param.setTrayNumber(trayCode+TrayNumber);//托盘编号
							TrayNumber++;
							ToolUtil.copyProperties(Tp,bTray);
							tList.add(bTray);
							bTray = new BasicTray();
						}
						param.setNum(detailedPutnum.toString());
						param.setBalenum(detailedPutnum.toString());
						param.setCanNum(detailedPutnum.toString());
						param.setStockWeight(w.multiply(detailedPutnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
						param.setStockVolume(v.multiply(detailedPutnum).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
						param.setUnitprice(u.toString());
						param.setStockMoney(u.multiply(detailedPutnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
						detailedPutnum = new BigDecimal(0);
					} else {
						param.setOperateId(Long.parseLong(basicWarehouse.getWarehouseOperateId().toString()));
						param.setOperateName(basicWarehouse.getWarehouseOperateName());
						param.setCustomerId(orderPut.getPutCustomerId());
						param.setCustomerName(orderPut.getPutCustomerName());
						param.setWarehouseId(orderPut.getWarehouseId());
						param.setWarehouseName(orderPut.getWarehouseName());
						param.setAreaId(Long.parseLong(basicPositionResult.getPositionAreaId().toString()));
						param.setAreaNumber(basicPositionResult.getAreaNumber());
						param.setPositionId(Long.parseLong(basicPositionResult.getId().toString()));
						param.setPositionNumber(basicPositionResult.getPositionNumber());
						param.setGoodsId(PutD.getDetailedGoodsnum());
						param.setGoodsNumber(PutD.getGoodsNumber());
						param.setGoodsName(PutD.getDetailedGoodsname());
						param.setProducetime(PutD.getDetailedDateofmanufacture());
						param.setGoodsbatchs(PutD.getDetailedBatchnumber());
						param.setPutTime(PutD.getRecommend());
						param.setStockstate("IN_STOCK");
						param.setDeptId(deptId);
						param.setDeliverId(deliverId);
						param.setCreateTime(new Date());

						BasicTrayParam trayParam = new BasicTrayParam();
						trayParam.setDeliverId(deliverId);
						trayParam.setDeptId(deptId);
						trayParam.setTrayState("IDLE");
						BasicTrayResult basicTrayResult = basicTrayService.findBySpec(trayParam,user.getOperateId());
						if (basicTrayResult != null) {
							param.setTrayNumber(basicTrayResult.getTrayNumber());
							basicTrayResult.setTrayState("OCCUPIED");
							ToolUtil.copyProperties(basicTrayResult, trayParam);
							basicTrayService.update(trayParam);
						} else {
							Tp.setTrayNumber(trayCode+TrayNumber);
							param.setTrayNumber(trayCode+TrayNumber);//托盘编号
							TrayNumber++;
							ToolUtil.copyProperties(Tp,bTray);
							tList.add(bTray);
							bTray = new BasicTray();
						}
						param.setNum(Supportvolume.toString());
						param.setBalenum(Supportvolume.toString());
						param.setCanNum(Supportvolume.toString());
						param.setStockWeight(w.multiply(Supportvolume).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
						param.setStockVolume(v.multiply(Supportvolume).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
						param.setUnitprice(u.toString());
						param.setStockMoney(u.multiply(Supportvolume).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
						detailedPutnum	=  detailedPutnum.subtract(Supportvolume);
					}
					ssPlist.add(param);
					param = new StorageStockParam();
				}
				if(ssPlist.size()>0) {
					storageStockService.batchAddList(ssPlist);
                    if (tList.size()>0) {
                    	basicTrayService.saveBatchList(tList);
                    }
				}
			}
		}
		
		OrderPutParam orderPutParam = new OrderPutParam();
		orderPutParam.setId(orderPut.getId());
		orderPutParam.setSubmissionTime(new Date());//提交时间
		orderPutParam.setSubmissionUser(user.getUserId());//提交user
		orderPutParam.setSubmissionName(user.getName());//提交人名称
		orderPutParam.setBillstate("WAREHOUSED");
		orderPutService.update(orderPutParam);
		return ResponseData.success();
	}

	@Override
	public List<StorageStockResult> finByOnlyOnePositionNumber(StorageStockParam sp) {
		return this.baseMapper.finByOnlyOnePositionNumber(sp);
	}

	@Override
	public List<StorageStockResult> finByOnlyOneOrderByGoodsbatchs(StorageStockParam sp) {
		return this.baseMapper.finByOnlyOneOrderByGoodsbatchs(sp);
	}

	@Override
	public void deleteBySpec(StorageStockParam param) {
		this.baseMapper.deleteBySpec(param);
	}

	@Override
	public LayuiPageInfo findStockPageBySpecPositionNumber(StorageStockParam storageStockParam,Long operateId) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.findStockPageBySpecPositionNumber(pageContext, storageStockParam, operateId);
        return LayuiPageFactory.createPageInfo(page);
	}

	@Override
	public LayuiPageInfo findGroupsStockPageBySpec(StorageStockParam storageStockParam,Long operateId) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.findGroupsStockPageBySpec(pageContext, storageStockParam, operateId);
        return LayuiPageFactory.createPageInfo(page);
	}

	@Override
	public void updateBySpec(StorageStockParam storageStockParam) {
		this.baseMapper.updateBySpec(storageStockParam);
	}

	@Override
	public Workbook exportToExcel(StorageStockParam storageStockParam) {
	    //这是表头
	    String[] arr = {"Status","Project","Customer","Warehouse","Storage Area","Storage Location","Pallet Number"
	    		,"Product","Code","Item No."
	    		,"Quantity","Pending Quantity"
	    		,"Inbound Batch","Production Date","Batch","Weight","Volume","Amount","Unit Price"
	    		,"Category","Unit","Packaging","Specifications","Shelf Life (days)"};
	    //这是具体数据
	    List<List<String>> list = new ArrayList<>();

    	User user = userService.getcurrentUser();
    	storageStockParam.setDeptId(user.getDeptId());
	    List<StorageStockResult> datalist = this.findExportToExcelBySpec(storageStockParam,user.getOperateId());
	    for (StorageStockResult r : datalist) {
		    List<String> list1 = new ArrayList<String>();
		    list1.add(r.getStockstate());
		    list1.add(r.getOperateName());
		    list1.add(r.getCustomerName());
		    list1.add(r.getWarehouseName());
		    list1.add(r.getAreaName());
		    list1.add(r.getPositionNumber());
		    list1.add(r.getTrayNumber());
		    list1.add(r.getGoodsName());
		    list1.add(r.getGoodsNumber());
		    list1.add(r.getGoodsNo());
		    list1.add(r.getNum());
		    list1.add(r.getStorageNumber());
		    list1.add(r.getPutTime());
		    list1.add(r.getProducetime());
		    list1.add(r.getGoodsbatchs());
		    list1.add(r.getStockWeight());
		    list1.add(r.getStockVolume());
		    list1.add(r.getStockMoney());
		    list1.add(r.getUnitprice());
		    list1.add(r.getGoodsBigtype());
		    list1.add(r.getGoodsUnit());
		    list1.add(r.getGoodsPacking());
		    list1.add(r.getGoodsSpecs());
		    list1.add(r.getGoodsWarranty());
		    list.add(list1);
		}
	    return ExcelWrite.writeToExcelByList(arr, list);
	}

	@Override
	public StorageStockResult findKwShuBySpec(StorageStockParam param) {
		return this.baseMapper.findKwShuBySpec(param);
	}

	/**
	 * 拣货位库存
	 * @param stockParam
	 * @return
	 */
    @Override
    public StorageStockResult sumbyJhwsqzkk(StorageStockParam stockParam) {
        return this.baseMapper.sumbyJhwsqzkk(stockParam);
    }

	@Override
	public String getKCCountByGoodsNumber(String detailedGoodscode,String positionType) {
		return this.baseMapper.getKCCountByGoodsNumber(detailedGoodscode,positionType);
	}

	@Override
	public String getDjhCountByGoodsNumber(String detailedGoodscode, Long deptId) {
		return this.baseMapper.getDjhCountByGoodsNumber(detailedGoodscode,deptId);
	}

	@Override
	public LayuiPageInfo findStockPageBySpecNew(StorageStockParam storageStockParam, String startPutTime, String endPutTime, String startSingleTime, String endSinglePutTime, Long operateId) {
		return null;
	}

	@Override
	public List<StorageStockResult> finByOnlyOnePositionNumber1(StorageStockParam storageOccupy) {
		return this.baseMapper.finByOnlyOnePositionNumber1(storageOccupy);
	}

	@Override
	public List<StorageStockResult> findListBySpec1(StorageStockParam storageStockParam, Long operateId) {
		return this.baseMapper.findListBySpec1(storageStockParam, operateId);
	}


	@Transactional(rollbackFor = Exception.class)
	@ResponseBody
	public ResponseData storageLimitItems(User user, String positionNumber1, Long warehouseId, String goodsNo, String goodsNumber, String batchNumber) {
		//根据库位号查询库位信息
		//商品  占用存储位数
		AtomicInteger occupyStorageCount = new AtomicInteger();
		//商品  占用拣货位数
		AtomicInteger occupySelectCount = new AtomicInteger();

		//库位  存放商品类数
		AtomicInteger storageClassCount = new AtomicInteger();

		//根据库位判断是拣选位还是储位位
		//准备上架库位
//			String positionNumber1 = storagePutSingleParam.getPositionNumber();
		BasicPositionParam basicPositionParam1 = new BasicPositionParam();
		basicPositionParam1.setPositionNumber(positionNumber1);
		BasicPositionResult preparePosition = basicPositionService.findBySpec(basicPositionParam1,user.getDeptId(),user.getOperateId());
		String positionType = preparePosition.getPositionType();

		//准备上架的库位商品占用情况
		StorageStockParam storageOccupy = new StorageStockParam();
		storageOccupy.setDeptId(user.getDeptId());
		storageOccupy.setWarehouseId(warehouseId);
		storageOccupy.setPositionNumber(positionNumber1);
		storageOccupy.setGoodsNumber(goodsNumber);
		storageOccupy.setGoodsbatchs(goodsNo);
		storageOccupy.setGoodsbatchs(batchNumber);
		List<StorageStockResult> storageStockResults = storageStockService.finByOnlyOnePositionNumber1(storageOccupy);
		storageClassCount.set(storageStockResults.size());

		//该商品 目前库存所在库位
		StorageStockParam storageStockParam = new StorageStockParam();
		storageStockParam.setDeptId(user.getDeptId());
		storageStockParam.setDeliverId(user.getDeliverId());
		storageStockParam.setGoodsNumber(goodsNumber);
		storageStockParam.setGoodsNo(goodsNo);

		List<StorageStockResult> stockPageBySpec = this.storageStockService.findListBySpec1(storageStockParam, user.getOperateId());

		stockPageBySpec.stream().forEach(data -> {
			//库位号
			String positionNumber = data.getPositionNumber();
			//判断是拣选位还是储位位
			//根据库位号查询库位信息
			BasicPositionParam basicPositionParam2 = new BasicPositionParam();
			basicPositionParam2.setPositionNumber(positionNumber);
			BasicPositionResult basicPosition = basicPositionService.findBySpec(basicPositionParam2,user.getDeptId(),user.getOperateId());
			if(basicPosition.getPositionType().equals("拣货位")) {
				occupySelectCount.getAndIncrement();
			} else if(basicPosition.getPositionType().equals("储位位")) {
				occupyStorageCount.getAndIncrement();
			}
		});
		if(positionType.equals("拣货位") ){
			//一位3品
			if(storageClassCount.get() >= 3) {
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				return ResponseData.error("该库位为拣货位,已存储3类商品，无法入库！");
			}
			//一品3位
			if(occupySelectCount.get() >= 3) {
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				return ResponseData.error("该库位为拣货位,该商品已占用3个拣货位，无法入库！");
			}
		}
		if(positionType.equals("存储位")){
			//一位一品
			if(storageClassCount.get() >= 1) {
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				return ResponseData.error("该库位位存储位,已存储1类商品，无法入库！");
			}
			//一品多位
		}
		return ResponseData.success();
	}
}
